0

I'm attempting to generate an evenly spaced array which needs to be very precise. A specific example would be an array from 690.4025 to 3968.85, in steps of exactly 1.9285.

Using numpy.arange() with floats results in an array which does not end at 3968.85, and there's some sort of weird systematic drift away from the "true" values of such an array.

How would you generate this kind of data if precision down to about 0.0001 is required for each value? Thanks in advance.

3
  • @not_a_robot: No, that's an entirely unrelated question. Commented Jan 4, 2017 at 20:23
  • 2
    Nate, there's an inconsistency in your question: where does 567.89 come from? Commented Jan 4, 2017 at 20:24
  • 1
    What do you mean "end at 567.89"? This number is not in the interval "690.4025 to 3968.85". Commented Jan 4, 2017 at 20:25

4 Answers 4

3

You can use numpy.linspace() to generate an array whose last element is exactly what you specify. In your example,

linspace(690.4025, 3968.85, (3968.85-690.4025)/1.9285)

should do it. Of course, some of the intermediate values may not be exactly representable as floating point numbers, so they might be inexact, but there's no way around that. If you're using 64-bit floats, the inaccuracy is on the order of 10-15 so it should still be within your tolerance.

Sign up to request clarification or add additional context in comments.

2 Comments

And even when the intermediates are exactly representable, you can still get rounding errors.
Thanks! This is what I was looking for.
1

you could just create an int array and then divide:

a = np.arange(6904025, 39688500, 19285) / 10000

also, to be clear, the original way you did has a total error on the order of 10^-8 (i.e., summing up all the differences between the int way and the float way), so that way should be more than precise enough.

2 Comments

Thanks. What I was missing seems to be that arange gives an array up to but not including the specified value, which inflated the "error".
yeah, it's like that for almost all ranges in python, except for maybe some pandas stuff.
1

numpy.linspace is designed for this task:

numpy.linspace(690.4025, 3968.85, num=whatever)

where num should be the number of elements you want in your array (including the endpoints), rather than the step size.

Comments

0

690.4025+1700*1.9285=3968.8525. So your start,stop,step seems to be irrelevant.

probably arange(690.4025,3969,1.9285) is what you want ?

[  690.4025,   692.331 ,   694.2595, ...,  3964.9955,  3966.924 ,
    3968.8525]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.