Benutzer:MovGP0/F♯/Root Finding Algorithmns

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Root Finding Algorithmns

[Bearbeiten | Quelltext bearbeiten]
  • zum Finden von Nullstellen

Bisection Method

[Bearbeiten | Quelltext bearbeiten]

Algorithm

let rec bisect n N (f:float -> float) (a:float) (b:float) (t:float) : float = 
   if n >= N 
   then -1.0
   else 
      let c = (a + b / 2)
      if f(c) = 0.0 || (b - a) / 2.0 < t then 
         c // solution
      else if sign(f(c)) = sign(f(a)) then 
         bisect (n+1) N f c b t
      else
         bisect (n+1) N f a c t

use

// define function
let f = (fun x -> (x**2.0 - x - 6))

let firstRoot  = bisect 0 25 f 0.0 10.0 0.01
let secondRoot = bisect 0 25 f -10.0 0.0 0.01
// n ... iteration start
// N ... max iteration
// f ... function to solve
// fprime ... first derivate of f
// x0 ... start value for x
// tol ... step size
let rec newtonRapson n N (f:float -> float) (fprime:float -> float) (x0:float) (tol:float) : float = 
   if n >= N 
   then
      -1.0
   else
      let d = fprime x0
      let newtonX = x0 - f(x0) / d
      if abs(d) < tol
      then
         -1.0
      else if abs(newtonX - x0) < tol
      then 
         newtonX
      else
         newtonRapson (n+1) N f fprime newtonX tol
let rec secant n N (f:float -> float) (x0:float) (x1:float) : float = 
    if n >= N 
    then 
        x0
    else
        let x = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
        secant (n + 1) N f x x0