Skip to content

Instantly share code, notes, and snippets.

@muhammadyaseen
Last active July 28, 2016 13:40
Show Gist options
  • Save muhammadyaseen/5590b5dab47a5ff2da3c to your computer and use it in GitHub Desktop.
Save muhammadyaseen/5590b5dab47a5ff2da3c to your computer and use it in GitHub Desktop.
Evaluate Riemann Sum for the given function, a good way to convince yourself about integrals
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RiemannSums
{
class Program
{
static double f( double x)
{
return x * x;
}
static double g(double x)
{
return 2*x * x + 3*x + 7;
}
static void Main(string[] args)
{
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}",0, 5, RiemannSumOf(f, 0, 5, 25 ),25);
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}", 0, 5, RiemannSumOf(f, 0, 5, 40),40);
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}", 0, 5, RiemannSumOf(f, 0, 5, 80),80);
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}", 0, 5, RiemannSumOf(g, 0, 5, 25), 25);
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}", 0, 5, RiemannSumOf(g, 0, 5, 40), 40);
Console.WriteLine(" x^2 from {0} to {1} with {3} cuts is {2}", 0, 5, RiemannSumOf(g, 0, 5, 80000), 80000);
}
/*
* Uses Left End point method
*/
static double RiemannSumOf( Func<double,double> func, double from , double to, int cuts)
{
double area = 0.0d;
int currentRect = 0;
double range = to - from;
double width = range/cuts;
double lastPoint = from;
while (currentRect != cuts)
{
currentRect++;
area += width * func((lastPoint + width));
lastPoint += width;
}
return area;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment