Skip to content

Instantly share code, notes, and snippets.

@tetsu-miyagawa
Last active December 4, 2015 13:53
Show Gist options
  • Save tetsu-miyagawa/a11fc3b40be55d7658ea to your computer and use it in GitHub Desktop.
Save tetsu-miyagawa/a11fc3b40be55d7658ea to your computer and use it in GitHub Desktop.
CTMCP Section 3.2.2 Figure 3.4
declare Sqrt SqrtIter Improve GoodEnough Abs
fun {Sqrt X}
Guess = 1.0
in
{SqrtIter Guess X}
end
fun {SqrtIter Guess X}
if {GoodEnough Guess X} then Guess
else
{SqrtIter {Improve Guess X} X}
end
end
fun {Improve Guess X}
(Guess + X/Guess) / 2.0
end
fun {GoodEnough Guess X}
{Abs X-Guess*Guess}/X < 0.00001
end
fun {Abs X}
if X < 0.0 then ~X
else X
end
end
{Browse {Sqrt 5.0}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment