Ask Your Question
1

boolean with numpy

asked 2013-09-29 08:28:25 +0100

AndreWin gravatar image

updated 2023-01-10 00:01:09 +0100

tmonteil gravatar image

Hello! Please explain me why

numpy.array([1/5])[0] == 0.2

is False but

numpy.array([1/5.])[0] == 0.2

is True. At 2nd line of code there is point after 5.
What should I do to get true at first line of code?
Thanks a lot.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2013-09-29 09:15:15 +0100

tmonteil gravatar image

updated 2013-09-29 09:19:35 +0100

For Sage, 1/5 is a rational number, whereas 1/5. is a floating point number:

sage: (1/5).parent()
Rational Field
sage: (1/5.).parent()
Real Field with 53 bits of precision

Now, when you put them in a numpy array, they are converted to a type named numpy.float64:

sage: type(numpy.array([1/5])[0])
<type 'numpy.float64'>
sage: type(numpy.array([1/5.])[0])
<type 'numpy.float64'>

As you can see, this conversion do not lead to the same approximation for 1/5 and 1/5., they seem not rounded to the same direction:

sage: numpy.float64(1/5)
0.19999999999999998
sage: numpy.float64(1/5.)
0.20000000000000001
sage: numpy.float64(0.2)
0.20000000000000001

This explains your problem. There are various issues about the rounding direction in Sage and the tools its uses, and i agree there should be a general audit.

Now, if you want 1/5 to be rounded in the right direction, you can first round it using RealField() which seems more consistent than numpy.float64:

sage: numpy.array([RR(1/5)])[0] == 0.2
True
edit flag offensive delete link more

Comments

Thanks a lot!)

AndreWin gravatar imageAndreWin ( 2013-09-29 09:19:35 +0100 )edit
0

answered 2013-10-19 17:52:42 +0100

tmonteil gravatar image

updated 2013-10-19 17:56:32 +0100

This has been fixed now (trac ticket #14416), so if you upgrade, you will now get:

sage: numpy.array([1/5])[0] == 0.2
True

sage: numpy.float64(1/5)
0.20000000000000001
edit flag offensive delete link more

Comments

Thanks a lot!)

AndreWin gravatar imageAndreWin ( 2013-10-20 07:16:05 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-09-29 08:28:25 +0100

Seen: 725 times

Last updated: Oct 19 '13