Print pi to a number of decimal places

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.


For example the mpmath package

from mpmath import mp
def a(n):
   mp.dps=n+1
   return(mp.pi)

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...

Great answers! there are so many ways to achieve this. Check out this method I used below, it works any number of decimal places till infinity:

#import multp-precision module
from mpmath import mp
#define PI function
def pi_func():
    while True:
        #request input from user
        try:
             entry = input("Please enter an number of decimal places to which the value of PI should be calculated\nEnter 'quit' to cancel: ")
             #condition for quit
             if entry == 'quit':
                 break
             #modify input for computation
             mp.dps = int(entry) +1
         #condition for input error
         except:
                print("Looks like you did not enter an integer!")
                continue
         #execute and print result
         else:
              print(mp.pi)
              continue

Good luck Pal!

Tags:

Python

Pi