Basic approximations in Python

Approximation means estimating the value of something that is not quite accurate, but almost correct. It plays a vital role in science and technology. Let`s start with the most common example. Have you ever used the exact pi value? Of course not. It is an infinite irrational number with a very long meaning. If we continue to write the exact value of Pi , perhaps even this article will not be enough for this:

 3.14159 26535 89793 23846 26433 83279 ... 

So here where approximation plays a role. We usually approximate Pi as 3.14 or in rational terms 22/7 . When you got to high school, you probably saw a wider application of approximations in mathematics, which use differentials to approximate the values ​​of quantities, such as (36.6) ^ 1/2 or (0.009) ^ 1/3. In computer science, we can use approximation to find the value or approximate the value of something using loops.

For example: approximation of the cube root of any number. Take a look at the process below:

# Python program to approximate
# cube root of 27

guess = 0.0

cube = 27

increment = 0.0001

epsilon = 0.1

# Find an approximate value

while abs (guess * * 3 - cube) & gt; = epsilon:

guess + = increment

# Check approximate value

if abs (guess * * 3 - cube) & gt; = epsilon:

  print ( "Failed on the cube root of" , cube)

else :

print (guess, " is close to the cube root of " , cube) 

Output of the above code:

 2.9963000000018987 is close to the cube root of 27  

As we can see, 2.99 is not the exact value of (27) ^ 1/3 but is very close to the exact value 3. This is what we call approximation. Here we have used a series of calculations to approximate the value. First, we declare a variable guess = 0.0 which we will keep incrementing in a loop until it approaches the cube root of 27. Another variable epsilon is chosen as little as possible to get more accurate meaning. The line while abs (guess ** 3 - cube) & gt; = epsilon: will take care of this. If it breaks out of the loop with a value greater than epsilon , it means that we have already crossed the approximate value and failed in the test. Otherwise, it will return the guess value.