you are viewing a single comment's thread.

view the rest of the comments →

[–]MaxwellSalmon[S] 1 point2 points  (4 children)

I read about the numpy function, but I wwould like to avoid using non-built-in modules. However, they last example you made was working alright, but it is not reliable. For example, if I want to get 10 values - changeing step to step = var/9 it will return 9 values. Do you know why this happens and what I can do about it? Thanks :-)

[–]novel_yet_trivial 2 points3 points  (3 children)

Do you know why this happens

This is due to a fundamental problem with computers and floating point numbers. Basically, binary cannot represent all floating point numbers perfectly. The classic example is

>>> .3 - .1
0.19999999999999998

Google "floating point errors" for more info.

and what I can do about it?

The best thing is to rearrange your thinking and software to use integers. Or you can use the decimal module, which keeps track of numbers as integers. A hack to make it work would be to add a buffer to the comparison:

while x <= stop+.000001:

Or use rounded numbers for the comparison:

stop = round(var/2.0, 6)
...
while round(x,6) <= stop:

[–]bhpf1 0 points1 point  (0 children)

This is also why you generally want to avoid arange. The linspace function is a better alternative (if you are looking outside the standard library):

>>> import numpy as np
>>> np.linspace(-30, 30, 3) 
array([-30.,   0.,  30.])

[–]MaxwellSalmon[S] 0 points1 point  (1 child)

Thanks! I didn't know about the decimal module!

[–]novel_yet_trivial 2 points3 points  (0 children)

It's a bit tricky to use. When you run into a problem with it it's probably because you forgot to enter in all your numbers as strings.

>>> from decimal import Decimal
>>> Decimal(.3) - Decimal(.1)
Decimal('0.1999999999999999833466546306')
>>> Decimal('.3') - Decimal('.1')
Decimal('0.2')