Open In App

Basic Approximations in Python

Last Updated : 11 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Approximation means to estimate the value of something which is not exactly but rather nearly correct. It plays a vital role in the field of science and technology. Let’s start with the most widely seen example. Have you ever used the exact value of Pi? Of course not. It is a non-terminating irrational number with a very long value. If we go on to write the exact value of Pi, probably even this article won’t be sufficient to do so:

3.14159 26535 89793 23846 26433 83279...

So here’s where approximation comes to play. We usually approximate the value of Pi as 3.14 or in terms of a rational number 22/7. When you advanced to your high school, you probably must have seen a larger application of approximations in Mathematics which uses differentials to approximate the values of quantities like (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: Approximating the cube root of any number. Take a look at the process below:




# Python program to approximate 
# the cube root of 27
guess = 0.0
cube = 27
increment = 0.0001
epsilon = 0.1
  
# Finding the approximate value
while abs(guess**3 - cube) >= epsilon:
    guess+=increment
  
# Checking the approximate value
if abs(guess**3 - cube) >= epsilon:
    print("Failed on the cube root of",cube)
else:
    print(guess,"is close to the cube root of",cube) 


The output of the above code is:

2.9963000000018987 is close to the cube root of 27

As we can see that 2.99 is not the exact value of (27)^1/3 but very close to the exact value 3. This is what we call approximation. Here we used a series of computations to approximate the value. First we declare a variable guess = 0.0 which we will keep on increasing in a loop until its close to the cube root of 27. Another variable epsilon is chosen as less as possible to get a more accurate value. The line while abs(guess**3 - cube) >= epsilon: takes care of this. If it exits the loop with a value greater than epsilon, it means that we already crossed the approximated value and failed on the test. Else, it will return the value of guess.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads