numpy cod溢出错误

2024-05-13 21:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些在计算中使用大整数的代码。由于我也使用了numpy,似乎有些变量被设置为type'数字.int64“这意味着它们过度流动。我怎么才能避开这个?在

如果您运行下面的代码,您将看到“调试信息”下的行。例如

19 1 72.7204246831 524288
19 2 2437717.7229 274877906944
19 3 149857055799.0 144115188075855872
19 4 1.73379003246e+16 0

其中前两列是n和w,最后一列是2**(n*w)。显然0是一个溢出错误。在

我怎么才能避开这个?在

^{pr2}$

Tags: 代码numpytype错误数字整数过度调试信息
2条回答

如果你要处理非常大的数字,你需要能够控制精度。看看python库mpmath

Mpmath is a pure-Python library for multiprecision floating-point arithmetic. It provides an extensive set of transcendental functions, unlimited exponent sizes, complex numbers, interval arithmetic, numerical integration and differentiation, root-finding, linear algebra, and much more. Almost any calculation can be performed just as well at 10-digit or 1000-digit precision, and in many cases mpmath implements asymptotically fast algorithms that scale well for extremely high precision work. Mpmath internally uses Python's builtin long integers by default, but automatically switches to GMP/MPIR for much faster high-precision arithmetic if gmpy is installed or if mpmath is imported from within Sage.

编辑:因为我可能在之前的回答中提供了上述代码:

https://stackoverflow.com/a/20576452/249341

我想重申,你应该在这里使用对数表示法,除非你需要一些组合计算的确切数字。使用log(x)代替x可以解决这种情况下的表示问题,而不需要使用mpmath。在

如果要超过64位整数范围,请使用浮点。否则,如果需要整数精度,但需要64位范围之外的值,则可以使用python Decimal对象。有关在numpy中使用Decimal的详细信息,请参见this answer。在

相关问题 更多 >