Roots of a function: Difference between revisions

Line 1,933:
Root found at 1
Root found at 2</pre>
 
=={{header|Phix}}==
{{trans|CoffeeScript}}
<lang Phix>procedure print_roots(integer f, atom start, atom stop, atom step)
-- Print approximate roots of f between x=start and x=stop, using
-- sign changes as an indicator that a root has been encountered.
atom x = start, y = 0
 
puts(1,"-----\n")
while x<=stop do
atom last_y = y
y = call_func(f,{x})
if y=0
or (last_y<0 and y>0)
or (last_y>0 and y<0) then
printf(1,"Root found %s %.10g\n", {iff(y=0?"at":"near"),x})
end if
x += step
end while
end procedure
 
-- Smaller steps produce more accurate/precise results in general,
-- but for many functions we'll never get exact roots, either due
-- to imperfect binary representation or irrational roots.
constant step = 1/256
 
function f1(atom x) return x*x*x-3*x*x+2*x end function
function f2(atom x) return x*x-4*x+3 end function
function f3(atom x) return x-1.5 end function
function f4(atom x) return x*x-2 end function
 
print_roots(routine_id("f1"), -1, 5, step)
print_roots(routine_id("f2"), -1, 5, step)
print_roots(routine_id("f3"), 0, 4, step)
print_roots(routine_id("f4"), -2, 2, step)</lang>
<pre>
-----
Root found at 0
Root found at 1
Root found at 2
-----
Root found at 1
Root found at 3
-----
Root found at 1.5
-----
Root found near -1.4140625
Root found near 1.41796875
</pre>
 
=={{header|PicoLisp}}==
7,820

edits