Roots of a function: Difference between revisions

Content deleted Content added
Line 369: Line 369:
=={{header|OCaml}}==
=={{header|OCaml}}==


A general root finder using the False Position (regula falsi) method, which will find all simple roots given a small step size.
A general root finder using the False Position (Regula Falsi) method, which will find all simple roots given a small step size.


<lang ocaml>
<lang ocaml>
let bracket u v =
let zcross u v = ((u > 0.0) && (v < 0.0)) || ((u < 0.0) && (v > 0.0));;
((u > 0.0) && (v < 0.0)) || ((u < 0.0) && (v > 0.0));;


let tol a b = (a = b);; (* or use a weaker tolerance *)
let xtol a b = (a = b);; (* or use |a-b| < epsilon *)


let rec regula_falsi a b fa fb f =
let rec regula_falsi a b fa fb f =
if tol a b then (a, fa) else
if xtol a b then (a, fa) else
let c = (fb*.a -. fa*.b)/.(fb-.fa) in
let c = (fb*.a -. fa*.b) /. (fb -. fa) in
let fc = f c in
let fc = f c in
if fc = 0.0 then (c, fc) else
if fc = 0.0 then (c, fc) else
if zcross fa fc then
if bracket fa fc then
regula_falsi a c fa fc f
regula_falsi a c fa fc f
else
else
Line 389: Line 390:
let rec next x fx =
let rec next x fx =
if x > hi then [] else
if x > hi then [] else
let y = x+.step in
let y = x +. step in
let fy = f y in
let fy = f y in
if fx = 0.0 then
if fx = 0.0 then
(x,fx) :: next y fy
(x,fx) :: next y fy
else if bracket fx fy then
(regula_falsi x y fx fy f) :: next y fy
else
else
if zcross fx fy then
next y fy in
(regula_falsi x y fx fy f) :: next y fy
else
next y fy in
next lo (f lo);;
next lo (f lo);;


Line 414: Line 414:
</pre>
</pre>


Note these roots are exact with floating-point accuracy.
Note these roots are exact solutions with floating-point calculation.


=={{header|Octave}}==
=={{header|Octave}}==