Skip to content

Instantly share code, notes, and snippets.

@gbluma
Last active December 14, 2015 19:58
Show Gist options
  • Save gbluma/5140262 to your computer and use it in GitHub Desktop.
Save gbluma/5140262 to your computer and use it in GitHub Desktop.
Using Simpson's rule to calculate integrals in Scala.
/** Desc: Using Simpson's rule to calculate integrals in Scala.
* Date: March 11, 2013
* Author: Garrett Bluma
*/
object Simpson
{
def sum(term:Double=>Double, a:Double, next:Double=>Double, b:Double):Double =
if (a > b) 0.0
else term(a) + sum(term, next(a), next, b);
def cube(a:Double):Double = a*a*a;
def simpson( f:Double=>Double, a:Double, b:Double, n:Double):Double = {
def y(f:Double=>Double,a:Double,h:Double)(k:Double):Double = f(a + k*h)
def next_n(n:Double):Double = n + 2.0
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))))
}
def main(args:Array[String]) {
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