python – numpy代码中的溢出错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – numpy代码中的溢出错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2397字,纯文字阅读大概需要4分钟。
内容图文
我有一些代码在计算中使用大整数.因为我也使用numpy,似乎有些变量被设置为类型’numpy.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是溢出错误.
我怎么能绕过这个?
#!/usr/bin/python
from __future__ import division
from scipy.misc import comb
from scipy.misc import factorial
import math
import numpy as np
N = 20
X = np.arange(2,N)
def k_loop_n(w,n):
K = np.arange(0, w+1)
return (comb(w,K)*(comb(w,K)/2**w)**n).sum()
def w_loop(n):
print "w loop"
v = [comb(n,w)*k_loop_n(w,n) for w in range(1,n+1)]
print v
return sum(v)
#This is meant to be an upper bound for sum (w choose i)^(n+1), i = 0..w
def sum_upper(i,n):
return (i+1)*((2**i)*math.sqrt(2/(i*np.pi))*(1-1/(4*i)))**(n+1)
def w_loop_upv2(n):
print "w loop upper bound"
print "debugging info"
print type(n)
for w in range(1,n+1):
print n, w, sum_upper(w,n), 2**(w*n)
v = [comb(n,w)*sum_upper(w,n)/2**(w*n) for w in range(1,n+1)]
return sum(v)
def upper_k_loop(w,n):
K = np.arange(0, w+1)
return (upperbin(w,K)*(upperbin(w,K)/2**w)**(3*float(n)/np.log(n))).sum()
def upper_w_loop(n):
v = [upperbin(n,w)*k_loop(w,n) for w in range(1,n+1)]
return sum(v)
print X
Y = [w_loop(n) for n in X]
Yupper = [w_loop_upv2(n) for n in X]
print Y
print Yupper
解决方法:
如果您打算使用非常大的数字,您将希望能够控制精度.看看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
我想重申你应该在这里使用logrithmic表示,除非你需要一些组合计算的确切数字.在这种情况下使用log(x)而不是x将解决表示问题而无需转到mpmath.
内容总结
以上是互联网集市为您收集整理的python – numpy代码中的溢出错误全部内容,希望文章能够帮你解决python – numpy代码中的溢出错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。