Created
January 6, 2023 22:50
-
-
Save luabida/ce15da52135a4682d92f35b8438cfa1c to your computer and use it in GitHub Desktop.
Square root calculator with Recursion.
This file contains hidden or 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
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