Python
/
Functions
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Approximate
➟
➟
Last update: 19-11-2021
Approximate
p 126 \[ \sqrt{4} = 2 \] One way of square roots is with Newton's method.
# Newton method:
#
# For finding roots ... assert distance(1, 2, 4, 6) == 0.0
# is a root-finding algorithm to produce succesive better aproximations
#
# Suppose that you want to know the square root of a.
# If you start with almost any estimate x ...
# you can compute a better estimation with the following formula:
# y = (x + a/x) / 2
#
# For example with a = 4, x = 3
# the result is preatty close to correct answer 2
# (3 + 4/3) / 2 = 2.16666666667
#
# If we repeat the process with the new estimate, it gets even closer
def square(a, x):
while True:
y = (x + a/x) / 2
if (y == x):
break
x = y
print(y)
return y
y = square(4, 10)
# 5.2
# 2.9846153846153847
# 2.1624107850911973
# 2.006099040777959
# 2.00000927130158
# 2.000000000021489
# 2.0
Float
p 128 In general it is dangerous to test float equality.
# Newton method v2
#
# In most programming languages, ...
# it is dangerous to test float equality, ...
# because floating-point values are only approximately right.
#
# It is safer to use the built-in function abs to compute the absolute value,
#
# epsilon: how close is close enought
def square(a, x, epsilon):
while True:
y = (x + a/x) / 2
print(y)
if abs(y - x) < epsilon:
break
x = y
y = square(64, 10, 0.0000001)
# 8.2
# 8.002439024390243
# 8.000000371689179
# 8.000000000000009
# 8.0
➥ Questions github Functions