Created
October 11, 2023 07:20
-
-
Save arjunKumbakkara/4a4b8a05b9bfdf72af1fabf3ff9b263b to your computer and use it in GitHub Desktop.
A beautiful demo of Callback in Python.Do visualize in PythonTutor Visualize
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
def sqrt(x, guess=0.1): | |
print("Trying:", guess, "-- Value:", guess*guess) | |
if good_enough(guess, x): | |
return guess | |
else: | |
guess = improve_guess(guess, x) | |
return sqrt(x, guess) | |
def good_enough(guess, x): | |
if abs(guess * guess - x) < 1: | |
return True | |
else: | |
return False | |
def avg(a, b): | |
return (a + b) / 2.0 | |
def improve_guess(guess, x): | |
return avg(guess, float(x)/guess) | |
def sqrt(x, is_ge=good_enough, guess=0.1): | |
print("Trying:", guess, "-- Value:", guess*guess) | |
if is_ge(guess, x): | |
return guess | |
else: | |
guess = improve_guess(guess, x) | |
return sqrt(x, is_ge, guess) | |
# By the nuclear reactor people | |
def very_accurate_good_enough(guess, x): | |
return abs(guess * guess - x) < 0.000000001 | |
sqrt(36, is_ge=very_accurate_good_enough) |
Author
arjunKumbakkara
commented
Oct 11, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment