Skip to content

Instantly share code, notes, and snippets.

@zidarsk8
Created April 22, 2013 20:07
Show Gist options
  • Save zidarsk8/5438072 to your computer and use it in GitHub Desktop.
Save zidarsk8/5438072 to your computer and use it in GitHub Desktop.
regula falsi
def regulaFalsi(eps:Double)(from:Double, to:Double, f: Double => Double) : Double = {
var i = 1000
var a = from
var fa = f(a)
var b = to
var fb = f(b)
var c = a - fa * (b-a)/(fb-fa)
var fc = f(c)
while (abs(fc)>eps && b-a > eps && {i-=1;i} > 0){
println(a,b,c,fa,fb,fc)
if (fa*fc < 0){
b = c
fb = fc
} else {
a = c
fa = fc
}
c = a - fa *(b-a)/(fb-fa)
fc = f(c)
}
c
}
@edofic
Copy link

edofic commented Apr 22, 2013

how about this instead?

def regulaFalsi(f: Double => Double)(from:Double, to:Double, eps:Double) : Double = {
  def step(i: Int, a: Double, fa: Double, b: Double, fb: Double): Double = {
    val c = c = a - fa *(b-a)/(fb-fa)
    val fc = f(c)
    if(abs(fc)>eps && b-a > eps && i > 0){
      println(a,b,c,fa,fb,fc)
      if (fa*fc < 0){
        step(i-1, a, fa, c, fc)
      } else {
        step(i-1, c, fc, b, fb)
      }
    } else c
  }
  step(1000, from, f(from), to, f(to))
}

DISCLAIMER: I didn't even try to compile this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment