Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 09:49
Show Gist options
  • Save AndrewBarfield/2556924 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556924 to your computer and use it in GitHub Desktop.
C#: How to perform Numerical Integration
using System;
namespace NumericalIntegration {
class Program {
static void Main(string[] args) {
int iterations = 100000;
double x, start, end, dist, sum = 0, sumT = 0;
Console.Write( "Input range start: " );
start = double.Parse( Console.ReadLine() );
Console.Write( "Input range end: " );
end = double.Parse( Console.ReadLine() );
dist = ( end - start ) / iterations;
for ( int i = 1 ; i <= iterations ; i++ ) {
x = start + i * dist;
sumT += f( x - dist / 2 );
if ( i < iterations ) {
sum += f( x );
}
}
sum = ( dist / 6 ) * ( f( start ) + f( end ) + 2 * sum + 4 * sumT );
Console.WriteLine( "Value on range [{0}, {1}] is around: {2}", start, end, sum );
Console.Read();
}
private static double f(double x) {
return Math.Sin(x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment