0

Here's a simple code in python.

end = np.zeros((11,2))
alpha=0
while(alpha<=1):
    end[int(10*alpha)] = alpha
    print(end[int(10*alpha)])
    alpha+=0.1
print('')
print(end)

and output:

[ 0.  0.]
[ 0.1  0.1]
[ 0.2  0.2]
[ 0.3  0.3]
[ 0.4  0.4]
[ 0.5  0.5]
[ 0.6  0.6]
[ 0.7  0.7]
[ 0.8  0.8]
[ 0.9  0.9]
[ 1.  1.]

[[ 0.   0. ]
 [ 0.1  0.1]
 [ 0.2  0.2]
 [ 0.3  0.3]
 [ 0.4  0.4]
 [ 0.5  0.5]
 [ 0.6  0.6]
 [ 0.8  0.8]
 [ 0.   0. ]
 [ 1.   1. ]
 [ 0.   0. ]]

​ It is easy to notice that 0.7 is missing and after 0.8 goes 0 instead of 0.9 etc... Why are these outputs differ?

2 Answers 2

1

It's because of floating point errors. Run this:

import numpy as np

end = np.zeros((11, 2))
alpha=0
while(alpha<=1):
    print("alpha is ", alpha)
    end[int(10*alpha)] = alpha
    print(end[int(10*alpha)])
    alpha+=0.1
print('')
print(end)

and you will see that alpha is, successively:

alpha is  0
alpha is  0.1
alpha is  0.2
alpha is  0.30000000000000004
alpha is  0.4
alpha is  0.5
alpha is  0.6
alpha is  0.7
alpha is  0.7999999999999999
alpha is  0.8999999999999999
alpha is  0.9999999999999999

Basically floating point numbers like 0.1 are stored inexactly on your computer. If you add 0.1 together say 8 times, you won't necessarily get 0.8 -- the small errors can accumulate and give you a different number, in this case 0.7999999999999999. Numpy arrays must take integers as indexes however, so it uses the int function to force this to round down to the nearest integer -- 7 -- which causes that row to be overwritten.

To solve this, you must rewrite your code so that you only ever use integers to index into an array. One slightly crude way would be to round the float to the nearest integer using the round function. But really you should rewrite your code so that it iterates over integers and coverts them into floats, rather than iterating over floats and converting them into integers.

You can read more about floating point numbers here:

https://docs.python.org/3/tutorial/floatingpoint.html

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

2 Comments

Yes, you can try int(10*(0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1)) and it will give 7 instead of 8. Use round() instead of int() to solve the problem.
Thanks, I have incorporated that into my answer.
1

As @Denziloe pointed, this is due to floating point errors.

If you look at the definition of int():

If x is floating point, the conversion truncates towards zero

To solve your problem use round() instead of int()

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.