27. round away from 0 solution is wrong
MarredCheese opened this issue · 8 comments
trunc() should be round(), like this:
print (np.round(Z + np.copysign(0.5, Z)))
Example: an original value of 1.4 becomes 1.9, which then rounds to 2 (correct) or truncates to 1 (incorrect).
Alternatively, this might be more readable, but maybe it teaches less. Maybe having multiple solutions for each problem would be most educational?
Z[Z<0] = np.floor(Z[Z<0])
Z[Z>0] = np.ceil(Z[Z>0])
print (Z)
Oh yes, forgot about negative value... Many thanks.
Could make a PR ?
Ok, will try do that soon.
On Tue, Jul 26, 2016 at 12:05 PM, Nicolas P. Rougier <
notifications@github.com> wrote:
Oh yes, forgot about negative value... Many thanks.
Could make a PR ?—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
#15 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AO-LbGQGWNKpQ3XKBFpTAOB73CQzYHcjks5qZj5TgaJpZM4JVPaJ
.
Thanks !
round() also doesn't work properly, as 1, 3, 5, ... are rounded to 2, 4, 6 (instead of 1, 3, 5)
I suggest following solution:
print(np.copysign(np.ceil(np.abs(Z)), Z))
What is your numpy version ? For me np.round(1.0)
gives me 1.0
Numpy 1.11.1
The code:
Z = np.array([1.0, 1.5, 2.0, 2.5, 3.0, 3.5])
print (np.round(Z + np.copysign(0.5, Z)))
for me prints:
[ 2. 2. 2. 3. 4. 4.]
while it should be:
[ 1. 2. 2. 3. 3. 4.]
I think this is because "For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value.", http://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html
Ah ok. Sorry, I did not understand your first example.
Could you make a PR with your changes ?
Yes, I wasn't clear in my first example.
I just created the PR. Please comment/modify in case I did anything wrong, as this is my first PR on github.
Thanks,