Task

Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.

The program should identify whether the root is exact or approximate.



For this task, use:      ƒ(x)   =   x3 - 3x2 + 2x 

procedure print_roots(integer f, atom start, stop, 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 = 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(f1, -1, 5, step)
print_roots(f2, -1, 5, step)
print_roots(f3,  0, 4, step)
print_roots(f4, -2, 2, step)
