Created
June 5, 2021 13:28
-
-
Save george124816/55978e9b019f75c8dc9a703e1433b3b0 to your computer and use it in GitHub Desktop.
Square Roots by Newton's Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Sqrt do | |
def sqrtiter(guess, x) do | |
if (goodenought?(guess, x)) do | |
guess | |
else | |
guess | |
|> improve(x) | |
|> sqrtiter(x) | |
end | |
end | |
def goodenought?(guess, x) do | |
guess | |
|> square | |
|> Kernel.-(x) | |
|> abs() | |
|> Kernel.<(0.001) | |
end | |
def improve(guess, x), do: average(guess, x / guess) | |
def average(x, y), do: (x + y) / 2 | |
def square(x), do: x * x | |
end | |
Sqrt.sqrtiter(1, 2) |> IO.puts() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment