Lin
Lin

Reputation: 1203

Creating a sequence of regularly spaced numbers

I create a sequence of regularly spaced numbers that naively could be taken defined with this simple code:

l=6          # Number of elements
h=1          # Spatial regular interval
v=[-h/2]     # First element
for i in range(l,start=1):
    v.append(v[-1]+h)

I'm using np.arange for that, as in:

np.arange(-h/2, h*(l-.5), h)

but documentation says that np.linspace should be used instead because I'm not using intergers.

np.linspace(-h/2, h*(l-.5), l, endpoint=False)

Is this approach fail proof?

Upvotes: 1

Views: 254

Answers (1)

Danilo Souza Morães
Danilo Souza Morães

Reputation: 1593

np.arange works by adding step to start and comparing if the result is >= stop in which case it will not generate this last value (endpoint), otherwise repeat the operation.

The problem is that floating point numbers can never be compared equal, because of the way they are represented in memory. Take this example for instance:

>>> 0.5 + 0.1 + 0.1 + 0.1 < 0.8
True

That behaviour of floating point numbers could cause a step=0.1 to be added to the previous generated value of np.arange of 0.7 and be less than the stop=0.8. This is why sometimes arange seems to return endpoint. It's not really returning endpoint, it's returning a number close to endpoint like 0.7999999999999999 which gets rounded up by the method thats returning the string representation of the floating point number.

This is not the case with np.linspace when you have a fixed number of steps, because you wont be comparing floating point numbers but rather calculating the value of a set number of steps. So answering your question, yes it is safe to use np.linspace the way you've done. Check this github thread for more information.

Note also that I've said you should have a fixed number of steps. If you are trying to calculate the number of steps based on start and stop you would run into similar problems as you can see on this other answer.

Upvotes: 1

Related Questions