Full Example — Rhomberg Integration

In numerical analysis, Romberg’s method (Romberg 1955) is a numerical approach used to estimate the definite integral \(\int_a^b f(x) dx\).

import math.pow
 
def romberg(f: Double => Double, a: Double, b: Double): Double = {
  def R(n: Int, m: Int): Double = (n, m) match {
    case (0, 0) => {
      0.5 * (b - a) * (f(a) + f(b))
    }
    case (_, 0) => {
      val hn = (b - a) / pow(2.0, n)
      val s = for (k < - 1 until pow(2, n-1).toInt) yield 
        f(a + hn * (2.0 * k - 1.0))
      0.5 * R(n - 1, 0) + hn * s.sum
    }
    case (_, _) => {
      val q4m = pow(4.0, m)
      val frac = 1.0 / (q4m - 1.0)
      frac * (q4m * R(n, m - 1) - R(n - 1, m - 1))
    }
  }
  R(20, 5)
}
 
def f(x: Double): Double = x * x + 2 * x + 1 
 
 
val r = romberg(f, 0, 5)
println("Integral de x * x + 2 * x + 1 em [0, 5] = " + r)