Ask Your Question
0

Bug or desired behavior of eval?

asked 13 years ago

process91 gravatar image

updated 11 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 13 years ago

DSM gravatar image

updated 13 years ago

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
Preview: (hide)
link

Comments

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

process91 gravatar imageprocess91 ( 13 years ago )

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: 13 years ago

Seen: 465 times

Last updated: Nov 22 '11