Quick actions

cmd+k|ctrl+k

Navigation

Languages

Newton-Raphson square root

Snippet info

Language

Ats

Visibility

public

Author

mindbound

Created

2016-11-22T08:54:15Z

Updated

2016-11-22T09:23:00Z

#include "share/atspre_staload.hats"
#include "share/atspre_define.hats"

#define EPS 1E-6

typedef fdouble = double -<cloref1> double

fun newton_raphson (f: fdouble, f': fdouble, x0: double): double = let
    fun loop (f: fdouble, f': fdouble, x0: double): double = let
        val y0 = f x0
    in
        if abs (y0 / x0) < EPS then x0 else
            let val y1 = f' x0 in loop (f, f', x0 - y0 / y1)
        end
    end
in
    loop (f, f', x0)
end

fn my_sqrt (c: double): double = newton_raphson (lam x => x * x - c, lam x => 2.0 * x, 1.0)

implement main0 () = () where
{
    val () = println! ("Square root of 9 = ", my_sqrt (9.0))
}
INFO