Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print pi to a number of decimal places

Tags:

python

pi

One of the challenges on w3resources is to print pi to 'n' decimal places. Here is my code:

from math import pi

fraser = str(pi)

length_of_pi = []

number_of_places = raw_input("Enter the number of decimal places you want to 
see: ")

for number_of_places in fraser:
    length_of_pi.append(str(number_of_places))

print "".join(length_of_pi)

For whatever reason, it automatically prints pi without taking into account of any inputs. Any help would be great :)

like image 575
Fraser Avatar asked Jul 31 '17 12:07

Fraser


People also ask

How do you calculate pi to a decimal?

There are essentially 3 different methods to calculate pi to many decimals. One of the oldest is to use the power series expansion of atan(x) = x - x^3/3 + x^5/5 - ... together with formulas like pi = 16*atan(1/5) - 4*atan(1/239). This gives about 1.4 decimals per term.

How do you round pi to 2 decimal places?

π rounded to 2 decimal places is 3.14 (3.141… is closer to 3.14 than to 3.15).


4 Answers

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...
like image 159
Jonas Adler Avatar answered Oct 21 '22 03:10

Jonas Adler


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.

like image 38
Moses Koledoye Avatar answered Oct 21 '22 02:10

Moses Koledoye


For example the mpmath package

from mpmath import mp
def a(n):
   mp.dps=n+1
   return(mp.pi)
like image 25
Abhishek Bahukhandi Avatar answered Oct 21 '22 03:10

Abhishek Bahukhandi


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!

like image 20
iykethe1st Avatar answered Oct 21 '22 04:10

iykethe1st