Last active
December 20, 2015 14:59
-
-
Save joshuawscott/6150854 to your computer and use it in GitHub Desktop.
Find a square root with elixir
(or just call :math.sqrt/1)
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 Math do | |
def sqrt(x) do | |
refine x, x / 2.0, 1.0 | |
end | |
def refine(target, _, attempt) when attempt * attempt == target do | |
attempt | |
end | |
def refine(_, adjustment, attempt) when abs(attempt - (attempt - adjustment)) < 1.0e-20 do | |
attempt | |
end | |
def refine(target, adjustment, attempt) when attempt*attempt > target do | |
refine(target, adjustment / 2, attempt - adjustment) | |
end | |
def refine(target, adjustment, attempt) when attempt*attempt < target do | |
refine(target, adjustment, attempt + adjustment) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment