Ask Your Question
0

Bug or desired behavior of eval?

asked 2011-11-22 18:00:07 +0100

process91 gravatar image

updated 2013-06-03 11:19:33 +0100

tmonteil gravatar image

I am fairly certain this is a bug, but I wanted to ask here before reporting it on trac. I understand that when we enter something in sage, like

sage: 5/3
5/3

We want to receive 5/3 instead of the normal python output:

>>> 5/3
1.6666666666666667

However, eval in sage seems to be rounding down:

sage: eval('5/3')
1

Where I would expect it to return 5/3 again, or at the very least 1.6666666666666667 (if eval ran through python first and had already returned 1.6666666666666667). The standard eval in python does return 1.6666666666666667.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2011-11-22 18:55:59 +0100

DSM gravatar image

updated 2011-11-22 19:01:01 +0100

Eval doesn't return 1.666...67 in python-- at least not in python 2, unless you import from the future.

Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 5/3
1
>>> eval('5/3')
1
>>> from __future__ import division
>>> eval('5/3')
1.6666666666666667

Switching to so-called true division was one of the incompatible changes between python 2 and python 3, one made among other reasons because it proved a pretty common mistake. (I made it myself several times in production code, and, come to think of it, it was the source of a number of bugs in Sage's graph plotting code.)

Python 3.2.1 (default, Jul 12 2011, 22:22:01) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> eval('5/3')
1.6666666666666667

Sage's underlying python is python 2, so integer division is truncating, and eval is doing the expected thing here. You can import from the future within Sage in the above way if you want to change the default behaviour, or use sage_eval instead:

----------------------------------------------------------------------
| Sage Version 4.7.2, Release Date: 2011-10-29                       |
| Type notebook() for the GUI, and license() for information.        |
----------------------------------------------------------------------
sage: 5/3
5/3
sage: eval('5/3')
1
sage: from __future__ import division
sage: eval('5/3')
1.6666666666666667
sage: sage_eval('5/3')
5/3
edit flag offensive delete link more

Comments

Thanks for clearing that up. I was using Python 3.

process91 gravatar imageprocess91 ( 2011-11-22 20:58:20 +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: 2011-11-22 18:00:07 +0100

Seen: 429 times

Last updated: Nov 22 '11