Approximation¶
Example: Approximating a Square Root¶
It is often the case in Computer science and Data Science that some value of interest is calculated by performing a sequence of better and better approximations. In these situations, we might tell our program precisely how many approximations we want it to perform (likely with a for
loop). Alternately, we might ask our program to continue to calculate approximations until we have met some condition, such as two subsequent approximations being very near to each other.
In the example below, we will approximate the square root of K = 7,341,234,543,244,549
. Our approach will be fairly simple. We will make an initial guess for the square root, which we will call x
. We will divide K
by x
, naming the result y
. If our guess was good, then x
and y
will be very close to each other, and thus close to the actual solution. If our guess was bad, we will set x
to be equal to the average of x
and y
, since the true answer will have to be somewhere between these two approximations.
We will continue this process until x
and y
are within 1/10000 of each other. So that we know how many times the loop had to run, we will also create a counter n
.
K = 7341234543244549
x = 1
y = K/x
n = 0
while abs(x - y) > 0.0001:
x = (x + y) / 2
y = K / x
n += 1
print('Value of x: ', x)
print('Value of y: ', y)
print('Value of x*y:', x**2)
print('Iterations: ', n)
Value of x: 85681004.56486577
Value of y: 85681004.56486577
Value of x*y: 7341234543244549.0
Iterations: 31
Example: Estimating Pi¶
We will close with one more example drawn from the world of mathematics. It can be proven that the transcendental number \(\pi\) can be written as a sum of infinitely many fractions as follows:
The more numbers we add in this never-ending series of fractions, the closer our approximation will be to the true value of \(\pi\). It can be shown that the amount of error involved in our approximation will be less than the absolute value of the first term from the series that we DID NOT add into the total.
In the cell below, we will add together several terms of this series, stopping when we reach a term whose absolute value is less than 0.00001.
pi_approx = 0
keep_adding = True
n = 0
while keep_adding:
new_term = 4 / (2*n + 1)
pi_approx = pi_approx + new_term * (-1)**n
n += 1
next_term = 4 / (2*n + 1)
if next_term < 0.00001:
keep_adding = False
print(pi_approx)
print(n)
3.1415876535897618
200000
Note that the first 8 decimal digits of pi are: 3.14159265