Multiply Very Large Numbers Accurately in Python

主宰稳场 提交于 2019-12-08 12:00:59

问题


I am trying to multiply very large floats by very large integers in Python and am noticing small inaccuracies. For example:

a = 45310630.0
b = 1023473145

c = int(a * b)
print(c)

The answer I am getting is 46374212988031352 but I know the answer should be 46374212988031350. When I change variable "a" to an integer, the multiplication is performed correctly. However, since "a" comes from a division (and might not be a whole number), I can't simply convert it to an integer.


回答1:


If you use fractions.Fraction you can handle larger numbers accurately, at the cost of some efficiency:

from fractions import Fraction
a = Fraction(45310630.0)
b = Fraction(1023473145)

c = int(a * b)
print(c)

Output:

46374212988031350

Some timings:

In [2]: a = Fraction(45310630.0)
   ...: b = Fraction(1023473145)
   ...:

In [3]: %timeit int(a * b)
3.92 µs ± 21.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [4]: a = 45310630.0
   ...: b = 1023473145
   ...:

In [5]: %timeit int(a * b)
479 ns ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)



回答2:


The reason that c is incorrect is due to how Python and other languages perform floating point math.

To circumvent this issue, you can use the fraction and decimal modules included in the standard library:

>>> a = 45310630.0
>>> b = 1023473145
>>> expected = 46374212988031350
>>> int(a * b) == expected
False

>>> from decimal import Decimal
>>> dec_a = Decimal.from_float(a)
>>> dec_b = Decimal.from_float(b)
>>> int(dec_a * dec_b) == expected
True

>>> from fraction import Fraction
>>> frac_a = Fraction.from_float(a)
>>> frac_b = Fraction.from_float(b)
>>> int(frac_a * frac_b) == expected
True


来源:https://stackoverflow.com/questions/49684411/multiply-very-large-numbers-accurately-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!