I am writing a Python program to compute the number π to as many decimal places as possible. My first difficulty was that I used variables float
that restricted the number of decimal places.
Thanks to forum suggestions, I switched to decimal
.
The fact is that the decimal approximation improved but only up to the 16th decimal, how it can be seen as follows:
π with my program
3.1415926535897931
667462219700150778696165489637681660703093062077
π with decimal value (math.pi)
3.1415926535897931
15997963468544185161590576171875
Here is the source code of my first program:
import math
from decimal import Decimal
import decimal
decimal.getcontext().prec = 65
a = Decimal(0)
valorN = 0
i = 3
pi = Decimal(0)
pi2 = Decimal(math.pi)
valorN = int(input('Ingrese el valor de n que sea mayor a 2 y menor a infinito: '))
a = decimal.Decimal(0)
while i <= valorN:
x1= decimal.Decimal(Decimal(2)+a).sqrt()
x = decimal.Decimal(Decimal(2)-x1).sqrt()
y = decimal.Decimal(pow(2,i-1))
pi = x*y
a = decimal.Decimal(Decimal(2)+a).sqrt()
i = i + 1
print('El valor de pi es ')
print(pi)
# este es el valor real #
print (pi2)