Thursday, 15 April 2010

python - NumPy linspace rounding error -



python - NumPy linspace rounding error -

could explain rounding issue numpy.linspace?

import numpy np np.linspace(0, 1, 6) == np.around( np.linspace(0, 1, 6), 10 ) # array([ true, true, true, false, true, true], dtype=bool)

here's how arrived here...

import numpy np ## 2 ways of defining same thing = np.array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ]) b = np.linspace(0, 1, 6) ## , b appear same # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ]) b # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ]) ## they're not == b # array([ true, true, true, false, true, true], dtype=bool) - b # array([ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -1.11022302e-16, 0.00000000e+00, 0.00000000e+00]) ## gotta round expected result c = np.round( np.linspace( 0, 1, 6 ), 10 ) c # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ]) == c # array([ true, true, true, true, true, true], dtype=bool)

the way defined b seems innocent plenty . . . rounding issue can bite on place?

it's not pretty, way floating point is, going have larn live it. weird result comes from:

>>> = np.float(1) >>> /= 5 >>> 0.2 >>> a*3 0.6000000000000001

you have np.allclose help deal kind of stuff, if not disciplined floating point comparisons yes, bite on , on again.

python numpy floating-point

No comments:

Post a Comment