qwaszxee qwaszxee - 6 days ago 6
Python Question

python float vs numpy.float give different answers?

Hello i don't understand what is happening with my code. The way numpy.float64 acts seems different from float.

i think they should give the same answers but they don't. 2e-05 vs 0.2

please help

main result

N = 500.0
1.0/N*(np.absolute((-1.2e-10 -1e+02j))) = 0.2
1.0/N*float(np.absolute(-1.2e-10 -1e+02j)) = 0.2
1.0/float(N*np.absolute(-1.2e-10 -1e+02j)) = 2e-05
N*np.absolute(-1.2e-10 -1e+02j) = 50000.0


code

print 'N*np.absolute(-1.2e-10 -1e+02j) = ',N*np.abs(-1.2e-10 -1e+02j)
print 'type(N*np.abs(-1.2e-10 -1e+02j))',type(N*np.abs(-1.2e-10 -1e+02j))
print '1/5000 = ',1/5000
print ''
print '1.0/N*np.absolute(-1.2e-10 -1e+02j) = ',1.0/N*np.abs(-1.2e-10 -1e+02j)
print 'type(1.0/N*np.abs(-1.2e-10 -1e+02j))',type(1.0/N*np.abs(-1.2e-10 -1e+02j))
print ''
print '1.0/N(*np.absolute((-1.2e-10 -1e+02j))) = ',1.0/N*(np.abs(-1.2e-10 -1e+02j))
print 'type(1.0/N*np.abs(-1.2e-10 -1e+02j))',type(1.0/N*(np.abs(-1.2e-10 -1e+02j)))
print ''
print '1.0/N*float(np.absolute(-1.2e-10 -1e+02j)) = ',1.0/N*float(np.abs(-1.2e-10 -1e+02j))
print 'type(1.0/N*float(np.absolute(-1.2e-10 -1e+02j)))',type(1.0/N*float(np.absolute(-1.2e-10 -1e+02j)))
print ''
print '1.0/float(N*np.absolute(-1.2e-10 -1e+02j)) = ',1.0/float(N*np.abs(-1.2e-10 -1e+02j))
print 'type(1.0/float(N*np.abs(-1.2e-10 -1e+02j)))',type(1.0/float(N*np.abs(-1.2e-10 -1e+02j)))


result

N*np.absolute(-1.2e-10 -1e+02j) = 50000.0
type(N*np.abs(-1.2e-10 -1e+02j)) <type 'numpy.float64'>
1.0/5000 = 0

1.0/N*np.absolute(-1.2e-10 -1e+02j) = 0.2
type(1.0/N*np.abs(-1.2e-10 -1e+02j)) <type 'numpy.float64'>

1.0/N(*np.absolute((-1.2e-10 -1e+02j))) = 0.2
type(1.0/N*np.abs(-1.2e-10 -1e+02j)) <type 'numpy.float64'>

1.0/N*float(np.absolute(-1.2e-10 -1e+02j)) = 0.2
type(1.0/N*float(np.absolute(-1.2e-10 -1e+02j))) <type 'numpy.float64'>

1.0/float(N*np.absolute(-1.2e-10 -1e+02j)) = 2e-05
type(1.0/float(N*np.abs(-1.2e-10 -1e+02j))) <type 'float'>


thanks for any help.

Answer

This is an order of operations issue. Use a few extra parenthesis...

>>> 1.0/N*float(np.absolute(-1.2e-10 -1e+02j))
0.2
>>> 1.0/(N*float(np.absolute(-1.2e-10 -1e+02j)))
2e-05
>>> 1.0/N*(np.absolute((-1.2e-10 -1e+02j)))
0.20000000000000001
>>> 1.0/(N*(np.absolute((-1.2e-10 -1e+02j))))
2.0000000000000002e-05

Basically, the difference is that you're comparing:

(1./N) * np.absolute((-1.2e-10 - 1e+02j))

with:

1./(N * np.absolute((-1.2e-10 - 1e+02j)))

And obviously those are going to have different values (irrespective of whether you're actually using float or np.float64).

Comments