The proposed solutions using np.pi, math.pi, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath package
>>> from mpmath import mp
>>> mp.dps = 20 # set number of digits
>>> print(mp.pi)
3.1415926535897932385
Using np.pi gives the wrong result
>>> format(np.pi, '.20f')
3.14159265358979311600
Compare to the true value:
3.14159265358979323846264338327...
Answer from Jonas Adler on Stack OverflowThe proposed solutions using np.pi, math.pi, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath package
>>> from mpmath import mp
>>> mp.dps = 20 # set number of digits
>>> print(mp.pi)
3.1415926535897932385
Using np.pi gives the wrong result
>>> format(np.pi, '.20f')
3.14159265358979311600
Compare to the true value:
3.14159265358979323846264338327...
Why not just format using number_of_places:
''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'
And more generally:
>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'
In your original approach, I guess you're trying to pick a number of digits using number_of_places as the control variable of the loop, which is quite hacky but does not work in your case because the initial number_of_digits entered by the user is never used. It is instead being replaced by the iteratee values from the pi string.
Videos
That is the Taylor series of at
(times 6).
This approximation for is attributed to Issac Newton:
- https://loresayer.com/2016/03/14/pi-infinite-sum-approximation/
- http://www.geom.uiuc.edu/~huberty/math5337/groupe/expresspi.html
- http://www.pi314.net/eng/newton.php
When I wrote that code shown in the Python docs, I got the formula came from p.53 in "The Joy of ฯ". Of the many formulas listed, it was the first that:
- converged quickly,
- was short,
- was something I understood well-enough to derive by hand, and
- could be implemented using cheap operations: several additions with only a single multiply and single divide for each term. This allowed the estimate of
to be easily be written as an efficient function using Python's floats, or with the decimal module, or with Python's multi-precision integers.
The formula solves for ฯ in the equation .
WolframAlpha gives the Maclaurin series for as:
Evaluating the series at gives:
From there, I used finite differences, to incrementally compute the numerators and denominators. The numerator differences were 8, 16, 24, ..., hence the numerator adjustment na+8 in the code. The denominator differences were 56, 88, 120, ..., hence the denominator adjustment da+32 in the code:
1 9 25 49 numerators
8 16 24 1st differences
8 8 2nd differences
24 80 168 288 denominator
56 88 120 1st differences
32 32 2nd differences
Here is the original code I wrote back in 1999 using Python's multi-precision integers (this predates the decimal module):
def pi(places=10):
"Computes pi to given number of decimal places"
# From p.53 in "The Joy of Pi". sin(pi/6) = 1/2
# 3 + 3*(1/24) + 3*(1/24)*(9/80) + 3*(1/24)*(9/80)*(25/168)
# The numerators 1, 9, 25, ... are given by (2x + 1) ^ 2
# The denominators 24, 80, 168 are given by 16x^2 +40x + 24
extra = 8
one = 10 ** (places+extra)
t, c, n, na, d, da = 3*one, 3*one, 1, 0, 0, 24
while t > 1:
n, na, d, da = n+na, na+8, d+da, da+32
t = t * n // d
c += t
return c // (10 ** extra)
Here is my code but when I search on github Some other codes which is not similar to mine but does the same job, so the question does my way is right or not?
import math
Pi = math.pi
ans = int(input("Enter the number of decimals to calculate to: "))
print(f"{pi:.{ans+1}}")
This is the code I saw on github:
https://github.com/MrBlaise/learnpython/blob/master/Numbers/pi.py
You can do what you want using format and specifying the number of places:
from math import pi
print (format (pi,'.100f'))
Another solution is by using the mpmath library:
from mpmath import mp
mp.dps = 100 # set number of digits
print(mp.pi)
Other answer are correct for printing with certain precision. However, if you try them with Decimal(math.pi) you will get 3.141592653589793115997963468544185161590576171875, obviously less than 100 digits, and even these digits are not all correct. Reason for this is that math.pi is float, which has limited precision.
To actually calcute correct digits of pi to any precision you can use this code (taken from official Python documentation for decimal library):
def pi():
"""Compute Pi to the current precision.
>>> print(pi())
3.141592653589793238462643383
"""
getcontext().prec += 2 # extra digits for intermediate steps
three = Decimal(3) # substitute "three=3.0" for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
getcontext().prec -= 2
return +s # unary plus applies the new precision
This presumes you have set getcontext().prec to wanted precision.