Skip to content

Instantly share code, notes, and snippets.

@gbluma
Created March 12, 2013 04:18
Show Gist options
  • Save gbluma/5140324 to your computer and use it in GitHub Desktop.
Save gbluma/5140324 to your computer and use it in GitHub Desktop.
Simpson's rule to calculate integrals in Felix. (Very similar to Scala version: http://gist.github.com/gbluma/5140262 )
/** Using Simpson's rule to calculate integrals in Felix
* Date: March 11, 2013
* Author: Garrett Bluma
h/3 (y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + ... + 2y_{n-2} + 4y_{n-1} + y_n)
where h = (b - a)/n for some even integer n
y_k = f(a + kh)
increasing n increases accuracy
*/
open System;
fun sum(term:double->double, a:double, next:double->double, b:double):double =>
if (a > b)
then 0.0
else term(a) + sum(term, next(a), next, b);
fun cube(a:double):double => a*a*a;
fun y(f:double->double,a:double,h:double)(k:double):double => f(a + k*h);
fun next_n(n:double):double => n + 2.0;
fun simpson( f:double->double, a:double, b:double, n:double):double = {
val h = (b - a)/n;
return (h / 3.0) * ( y(f,a,h)(0.0)
+ y(f,a,h)(n)
+ (4.0 * sum( y(f,a,h), 1.0, next_n, (n - 1.0)))
+ (2.0 * sum( y(f,a,h), 2.0, next_n, (n - 2.0))));
}
println$ simpson( cube, 0.0, 1.0, 2.0 );
// => 0.25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment