Skip to content

Instantly share code, notes, and snippets.

@joshuawscott
Last active December 20, 2015 14:59
Show Gist options
  • Save joshuawscott/6150854 to your computer and use it in GitHub Desktop.
Save joshuawscott/6150854 to your computer and use it in GitHub Desktop.
Find a square root with elixir (or just call :math.sqrt/1)
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