Python
/
Functions
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Functions Approximate
Square root y = (x + a/x) / 2 y == x #break x = y ... Repeat
Approximate
p126\[ \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
p128 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