In: Computer Science
Write a Python 3 code that takes an irrational number 'x' and return 'm' fraction approximations. For example let x=pi and m=4, then the program should return 4 examples of pi written as a fraction approximation.
The code which takes an irrational number x and returns the given number of fraction approximations is given below and will be explained below -
from fractions import Fraction
import math
x = float(input('Enter irrational number: '))
m = int(input('Enter number of fraction approximations: '))
c=10
for i in range(1,m+1):
res = Fraction(x).limit_denominator(int(math.pow(c,i)))
print(res)
Explanation -
Output -
As it is seen in the output screenshot, the entered irrational number is pi(3.141592) and I want 4 function approximations. Now if you see the output, we have the denominators limited to 10,100,1000 and so on. So the first approximation comes out to be 22/7 which is expected.