回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在使用numpy对数组求和,但它不适用于float32类型。我做错什么了?一旦我直接求和,然后我用数字总和. 请参阅下面的代码</p>
<pre><code>import struct
import numpy as np
import matplotlib.pyplot as plt
import math
from pylab import *
xpt=128
ypt=128
zpt=256
bx1=np.zeros((xpt,ypt,zpt),dtype=float32)
bx2=np.zeros((xpt,ypt,zpt),dtype=float32)
bx3=np.zeros((xpt,ypt,zpt),dtype=float32)
bx1=bx1+1.0
bx2=bx2+1.5
bx3=bx3+2.0
dummy=0.0
for kxi in range (0,xpt) :
for kyi in range (0,ypt) :
for kzi in range (0,zpt) :
dummy=dummy+(bx1[kxi,kyi,kzi]*bx1[kxi,kyi,kzi]+bx2[kxi,kyi,kzi]*bx2[kxi,kyi,kzi]+bx3[kxi,kyi,kzi]*bx3[kxi,kyi,kzi])
print(dummy)
print(np.sum(bx1**2+bx2**2+bx3**2))
</code></pre>
<p>两个输出应该匹配。输出结果:<br/>
30408704.0<br/>
3.1323e+07</p>
<p>直接和给出了正确的结果,而np.总和是给错了什么。但是,如果我使用float64,那么np.总和给出正确的结果。这背后的原因是什么?在</p>
<p>谢谢。在</p>