Skip to content

Instantly share code, notes, and snippets.

@luabida
Created January 6, 2023 22:50
Show Gist options
  • Save luabida/ce15da52135a4682d92f35b8438cfa1c to your computer and use it in GitHub Desktop.
Save luabida/ce15da52135a4682d92f35b8438cfa1c to your computer and use it in GitHub Desktop.
Square root calculator with Recursion.
def next_(n, x):
return (x + n / x) / 2
# Repeats infinitely
def repeat(f, a):
yield a
for v in repeat(f, f(a)):
yield v
# Delimiter
def within(ε, iterable):
def head_tail(ε, a, iterable):
b = next(iterable)
if abs(a-b) <= ε:
return b
return head_tail(ε, b, iterable)
return head_tail(ε, next(iterable), iterable)
def sqrt(a0, ε, n):
return within(ε, repeat(lambda x: next_(n,x), a0))
sqrt(1.0, .0001, 2) #Same as √2
sqrt(1.0, .0001, 3) #Same as √3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment