Q36 : np.ceil yield wrong answer
zhukpm opened this issue · 2 comments
zhukpm commented
Q: Extract the integer part of a random array using 5 different methods
A:
...
print (np.ceil(Z)-1)
....
But it yields wrong results when float numbers have only integer part:
In[]:
Z = np.random.uniform(0,10,10)
Z = np.hstack([Z, [1., -1.]])
print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
Out[]:
[ 4. 1. 2. 6. 0. 9. 0. 8. 4. 8. 1. -1.]
[ 4. 1. 2. 6. 0. 9. 0. 8. 4. 8. 1. -1.]
[ 4. 1. 2. 6. 0. 9. 0. 8. 4. 8. 0. -2.]
[ 4 1 2 6 0 9 0 8 4 8 1 -1]
[ 4. 1. 2. 6. 0. 9. 0. 8. 4. 8. 1. -1.]
Should be removed.
rougier commented
Oh, good point and I don't think it can be fixed easily (using ceil
I mean). Maybe we can restrict the question to 4 methods. Can you make a PR ?
zhukpm commented
Oh, good point and I don't think it can be fixed easily (using
ceil
I mean). Maybe we can restrict the question to 4 methods. Can you make a PR ?
Sure.
By the way, there's also different behaviours when handling positive and negative numbers. See an example:
a = np.array([3.03, -3.03, 0.69, -0.69, 0., 1., -1.])
print(a)
print(a - a % 1)
print(np.floor(a))
print(np.ceil(a) - 1)
print(a.astype(int).astype(float))
print(np.trunc(a))
Results in
[ 3.03 -3.03 0.69 -0.69 0. 1. -1. ]
[ 3. -4. 0. -1. 0. 1. -1.]
[ 3. -4. 0. -1. 0. 1. -1.]
[ 3. -4. 0. -1. -1. 0. -2.]
[ 3. -3. 0. 0. 0. 1. -1.]
[ 3. -3. 0. -0. 0. 1. -1.]
So I suggest restrict it for positive numbers only and remove ceil
. What do you think?