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 

 
#include
"share/atspre_staload.hats"
 
typedef d = double
 
fun
findRoots
(
  start: d, stop: d, step: d, f: (d) -> d, nrts: int, A: d
) : void = (
//
if
start < stop
then let
  val A2 = f(start)
  var nrts: int = nrts
  val () =
  if A2 = 0.0
    then (
      nrts := nrts + 1;
      $extfcall(void, "printf", "An exact root is found at %12.9f\n", start)
    ) (* end of [then] *)
  // end of [if]
  val () =
  if A * A2 < 0.0
    then (
      nrts := nrts + 1;
      $extfcall(void, "printf", "An approximate root is found at %12.9f\n", start)
    ) (* end of [then] *)
  // end of [if]
in
  findRoots(start+step, stop, step, f, nrts, A2)
end // end of [then]
else (
  if nrts = 0
    then $extfcall(void, "printf", "There are no roots found!\n")
  // end of [if]
) (* end of [else] *)
//
) (* end of [findRoots] *)
 
(* ****** ****** *)
 
implement
main0 () =
findRoots (~1.0, 3.0, 0.001, lam (x) => x*x*x - 3.0*x*x + 2.0*x, 0, 0.0)
 