Print pi to a number of decimal places

前端 未结 7 2469
感情败类
感情败类 2020-12-19 08:56

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 = []

numbe         


        
7条回答
  •  不思量自难忘°
    2020-12-19 09:27

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

提交回复
热议问题