Is there better alternative to Numpy arange()?

For the code below, I want the range to stop at value 1.0, but it keeps going up to 1.099999..., which makes sense as it's a float value.

What would be the better way to create this range with step of 0.1?

import numpy as np
start = 0.5
stop = 1.0
step = 0.1
for parameter_value in np.arange(start, stop + step, step): print(parameter_value)

Output

0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
4

2 Answers

You can not represent 0.1 exactly in binary IEEE 754 format, which is what most modern architectures use internally to represent floating point numbers.

The closest binary value to 0.1 is just a shade under truth. When you add this nearest approximation five times, the error will increase.

According to the docs for np.arange:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.

The reason is that by clamping the ends, linapace can make some assurances about the cumulative error which arange can not. Each individual step used by linspace may not be the closest binary representation of 0.1, but each element will be as close as possible to n * 0.1 from the start and end.

The linapace call corresponding to np.arange(0.5, 1.1, 0.1) is

np.linspace(0.5, 1.0, 6)

The other advantage of linspace is that you fix the number of points. Also according to the arange docs (the return value):

For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.

As an alternative, you can use the fact that division doesn't incur as much error as iterated addition. This is as precise as floating point arithmetic can get you:

np.arange(5, 11) / 10.0
# => array([0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

(np.linspace uses a very similar formula, though as long as you are working with rational numbers, the code above may be easier to grasp in your use case - you don't have to calculate the number of steps yourself.)

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like