[SciPy-user] Problem with arange

Francesc Alted falted at openlc.org
Tue Nov 4 13:16:55 EST 2003


A Dimarts 04 Novembre 2003 18:45, Santiago Erquicia va escriure:
> I'm using Numeric.arange and I have different results depending on the
> numbers I'm using.
>
> For example:
> arange(9, 12.1, 0.1, Float)
> arange(18, 21.1, 0.1, Float)
>
> The difference is that the first one doesn't include the max value, but
> the second one do this.

This is a typical problem with float representation on a machine. Look at
that:

>>> 12.1
12.1
>>> 21.1
21.100000000000001

so, many floating point numbers has not an exact representation. In your
case, 21 < 21.100000000000001, so these rounding problems are causing that
kind of problems.

A workaround on that is to define a very small number compared with your
step size (but still larger than the machine precision for this type!), and
this will get solved:

>>> epsilon = 1e-15
>>> arange(9, 12.1+epsilon, 0.1, Float)
array([  9. ,   9.1,   9.2,   9.3,   9.4,   9.5,   9.6,   9.7,   9.8,
         9.9,  10. ,  10.1,  10.2,  10.3,  10.4,  10.5,  10.6,  10.7,
        10.8,  10.9,  11. ,  11.1,  11.2,  11.3,  11.4,  11.5,  11.6,
        11.7,  11.8,  11.9,  12. ,  12.1])
>>> arange(18, 21.1+epsilon, 0.1, Float)
array([ 18. ,  18.1,  18.2,  18.3,  18.4,  18.5,  18.6,  18.7,  18.8,
        18.9,  19. ,  19.1,  19.2,  19.3,  19.4,  19.5,  19.6,  19.7,
        19.8,  19.9,  20. ,  20.1,  20.2,  20.3,  20.4,  20.5,  20.6,
        20.7,  20.8,  20.9,  21. ,  21.1])

(or do a substraction if you don't want the upper limit to be included, in
the pure python tradition)

Cheers,

-- 
Francesc Alted



More information about the SciPy-User mailing list