简体   繁体   English

numpy.int64和/或numpy.float64存在奇怪的基本计算问题?

[英]Strange basic computation issue with numpy.int64 and/or numpy.float64?

I am getting a very weird and unexpected ERROR from python-numpy 我从python-numpy得到一个非常奇怪和意想不到的错误

I am working with the following libraries: 我正在使用以下库:

import os, glob, string, math, csv, json
import datetime as dt
import numpy as np
import scipy as sci
import pandas as pd
import matplotlib.pyplot as plt
import feedparser as fp
import cPickle as pickle
import networkx as nx
from urllib2 import urlopen
import statsmodels.formula.api as sm
import patsy

The following code: 以下代码:

n,k = 2643605051, 648128.068241
print n,type(n)
print k, type(k)
nkvar = (k + 1)*(n + 2)/( (n+2) * (n+1)**2 )
print nkvar

n = np.int64(n)
k = np.float64(k)
print n,type(n)
print k, type(k)
nkvar = (k + 1)*(n + 2)/( (n+2) * (n+1)**2 )
print nkvar

Yields: 产量:

2643605051 <type 'int'>
648128.068241 <type 'float'>
9.27402694708e-14
2643605051 <type 'numpy.int64'>
648128.068241 <type 'numpy.float64'>
-0.00383719008751

The second answer is OBVIOUSLY wrong! 第二个答案是错误的! Could someone please help me understand what is going on? 请有人帮我理解发生了什么事吗?

You are suffering from arithmetic overflow. 你正在遭受算术溢出。 With NumPy, for the sake of speed, most operations do not check for arithmetic overflow . 对于NumPy,为了速度, 大多数操作都不检查算术溢出 The onus is on you to choose the proper dtype to avoid overflow. 您有责任选择合适的dtype以避免溢出。

import numpy as np

n,k = 2643605051, 648128.068241
nkvar = (k + 1)*(n + 2)/((n+1)**2 * (n+2))
print "In foo nkvar = ", nkvar, "  from (n,k) = ", (n,k)
# In foo nkvar =  9.27402694708e-14   from (n,k) =  (2643605051L, 648128.068241)       

n,k = np.int64(2643605051), np.float32(648128.068241)
nkvar = (k + 1)*(n + 2)/((n+1)**2 * (n+2))
print "In foo nkvar = ", nkvar, "  from (n,k) = ", (n,k)
# In foo nkvar =  -0.00383719005352   from (n,k) =  (2643605051, 648128.06)

A workaround: Since there is no NumPy integer dtype large enough to perform the computation without overflow, you'll need to convert n to a Python int first: 解决方法:由于没有足够大的NumPy整数dtype可以在没有溢出的情况下执行计算,因此您需要首先将n转换为Python int:

n = int(w.sum())

Another alternative is to change the dtype of n to float64 : 另一种方法是将ndtype更改为float64

n,k = np.float64(2643605051), np.float64(648128.068241)
nkvar = (k + 1)*(n + 2)/((n+1)**2 * (n+2))
print "In foo nkvar = ", nkvar, "  from (n,k) = ", (n,k)
# In foo nkvar =  9.27402694708e-14   from (n,k) =  (2643605051.0, 648128.06824099994)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM