问题描述
我试图在Python中将很大的浮点数乘以很大的整数,并注意到很小的不准确性.例如:
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)
我得到的答案是46374212988031352,但我知道答案应该是46374212988031350.当我将变量"a"更改为整数时,可以正确执行乘法.但是,由于"a"来自除法(可能不是整数),所以我不能简单地将其转换为整数.
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.
推荐答案
如果使用 fractions.Fraction
,您可以准确地处理较大的数字,但需要付出一定的效率:
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)
输出:
46374212988031350
一些时间:
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)
这篇关于在Python中准确地乘以非常大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!