Jump to content

Roots of a function: Difference between revisions

Line 366:
Out[6]= x==0||x==1||x==2
(note that this doesn't yield a "solution" but a different expression that expresses the same thing as the original)
 
=={{header|Ocaml}}==
 
A general root finder using the False Position (regula falsi) method.
 
<lang ocaml>
let zcross u v = ((u > 0.0) && (v < 0.0)) || ((u < 0.0) && (v > 0.0));;
 
let tol a b = (a = b);; (* or use a weaker tolerance *)
 
let rec regula_falsi a b fa fb f =
if tol a b then (a, fa) else
let c = (fb*.a -. fa*.b)/.(fb-.fa) in
let fc = f c in
if fc = 0.0 then (c, fc) else
if zcross fa fc then
regula_falsi a c fa fc f
else
regula_falsi c b fc fb f;;
 
let search lo hi step f =
let rec next x fx =
if x > hi then [] else
let y = x+.step in
let fy = f y in
if fx = 0.0 then
(x,fx) :: next y fy
else
if zcross fx fy then
(regula_falsi x y fx fy f) :: next y fy
else
next y fy in
next lo (f lo);;
 
let showroot (x,fx) =
Printf.printf "f(%.17f) = %.17f [%s]\n"
x fx (if fx = 0.0 then "exact" else "approx") in
let f x = ((x -. 3.0)*.x +. 2.0)*.x in
List.map showroot (search ~-.5.0 5.0 0.1 f);;
</lang>
 
Output:
<pre>
f(0.00000000000000000) = 0.00000000000000000 [exact]
f(1.00000000000000022) = 0.00000000000000000 [exact]
f(1.99999999999999978) = 0.00000000000000000 [exact]
</pre>
 
=={{header|Octave}}==
Line 407 ⟶ 454:
x = x + step;
endwhile</lang>
 
 
=={{header|Perl}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.