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))
Both outputs should match. This gives the output:
30408704.0
3.1323e+07
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?
Thanks.