当前位置: 动力学知识库 > 问答 > 编程问答 >

more decimal places needed in python

问题描述:

I am writing a python code, which needs to asses number to very many decimal places - around 14 or 15.

I expect results that increase smoothly, for example:

0.123456789101997

0.123456789101998

0.123456789101999

0.123456789102000

0.123456789102001

But I seem to be only getting numbers (when I print them out) to 12 decimal places, so my numbers are actually jumping in steps:

0.123456789101

0.123456789101

0.123456789101

0.123456789102

0.123456789102

At first, I assumed that the number was listed to more decimal places behind the scenes, but just printed out to 12, but when I print the results, they seem to plot in steps also, rather than smoothly.

I'd be really grateful if anyone would point me in the right direction to fix this - thank you.

网友答案:

How about trying the Decimal module?

In [2]: import decimal

In [3]: d = decimal.Decimal('0.123456789101997')

In [4]: print d
0.123456789101997
网友答案:

Use repr(), print uses str() which reduces the number of decimal digits to 12 to make the output user friendly.

In [17]: a=0.123456789101997

In [18]: str(a)
Out[18]: '0.123456789102'

In [19]: repr(a)
Out[19]: '0.123456789101997'

or string formatting:

In [21]: "{0:.15f}".format(a)
Out[21]: '0.123456789101997'
网友答案:

You can use Decimal for better precision.

网友答案:

As suggested in previous answers, you can use Decimal numbers via the decimal module, or alternately can specify 15 decimal places when printing floating point values, to override the default of 12 places.

In many Python implementations, ordinary floating point numbers are IEEE 754-compatible (1, 2) “binary64” double precision numbers, so have effectively 53 bits in their mantissas. As 53*math.log(2)/math.log(10) is about 15.95, binary64 numbers support more than 15 decimal digits of precision but not quite 16.

Here is an example you can try, shown with its output:

u=1e-15
v=0.123456789101997
for k in range(13):print '{:20.15f}'.format(v+k*u)
   0.123456789101997
   0.123456789101998
   0.123456789101999
   0.123456789102000
   0.123456789102001
   0.123456789102002
   0.123456789102003
   0.123456789102004
   0.123456789102005
   0.123456789102006
   0.123456789102007
   0.123456789102008
   0.123456789102009
分享给朋友:
您可能感兴趣的文章:
随机阅读: