numpy的总和没有为float32类型给出正确的答案 [英] numpy sum is not giving right answer for float32 type

查看:278
本文介绍了numpy的总和没有为float32类型给出正确的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用numpy求和一个数组,它不适用于float32类型.我究竟做错了什么?一旦我直接进行求和,然后使用numpy.sum.参见下面的代码

I am summing an array using numpy, and it isn't working for float32 type. What am I doing wrong? Once I do a sum directly, and then I use numpy.sum. See the code below

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))

两个输出应该匹配.这给出了输出:
30408704.0
3.1323e + 07

Both outputs should match. This gives the output:
30408704.0
3.1323e+07

直接和给出正确的结果,而np.sum给出错误的结果.但是,如果我使用float64,则np.sum会给出正确的结果.这是什么原因造成的?

The direct sum gives the correct result, whereas np.sum is giving something wrong. However, if I use float64, then np.sum gives the correct result. What is the reason behind this?

谢谢.

推荐答案

float32的精度这么大是个问题.我还没有遍历2.25的存储方式,但是最小的例子

It is a problem with the accuracy of float32 with a number that big. I haven't run through how 2.25 would be stored, but the minimal example

x = 2.25 * np.ones((128, 128, 256), dtype = float32)
y = 2.25 * np.ones((128, 128, 256), dtype = float64)
x.sum() # 8854642.0
y.sum() # 9437184.0
2.25 * 128 * 128 * 256 # 9437184.0

表明您失去了准确性,但是却使用float64获得了准确性(python的标准浮动).

Shows that you lose accuracy, but gain it back with float64 (python's standard float).

这篇关于numpy的总和没有为float32类型给出正确的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆