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 main()
    showRoots(f, -1.0, 4, 0.002)
end
 
procedure f(x)
    return x^3 - 3*x^2 + 2*x
end
 
procedure showRoots(f, lb, ub, step)
    ox := x := lb
    oy := f(x)
    os := sign(oy)
    while x <= ub do {
        if (s := sign(y := f(x))) = 0 then write(x)
        else if s ~= os then {
            dx := x-ox
            dy := y-oy
            cx := x-dx*(y/dy)
            write("~",cx)
            }
        (ox := x, oy := y, os := s)
        x +:= step
        }
end
 
procedure sign(x)
    return (x<0, -1) | (x>0, 1) | 0
end