且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中准确地乘以非常大的数字

更新时间:2023-02-19 22:45:19

如果使用

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)