Unintuitive behavior of round()

47 views
Skip to first unread message

Lorenzo

unread,
May 13, 2012, 12:50:11 PM5/13/12
to sage-s...@googlegroups.com
Hi everyone, first time sage user here.

I am puzzled by the behavior of round():

sage: t=sqrt(4320373582484102551677386613153502)
sage: floor(t)
65729548777426599
sage: round(t) #everything as expected, floor ≤ round ≤ ceil
65729548777426600
sage: ceil(t)
65729548777426600
sage: u = sqrt(43203735824841025516773866131535024) #add one digit
sage: floor(u)
207855083711803944
sage: round(u) # ?? smaller than floor(u)! No warning message...
207855083711803936
sage: r = round(u)
sage: ceil(u)
207855083711803945
sage: type(r) # seems to have still the same precision...? (i.e., it wasn’t converted to some "float type" – I admit of course that I don't know how the sage type system works)
<type 'sage.rings.integer.Integer'>
sage: version()
'Sage Version 4.8, Release Date: 2012-01-20'

uname -a
Darwin iMac.local 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

Can someone explain this behavior? If this isn’t a bug, it is a very unintuitive "feature" for sage-neophytes, to say the least.

Thank you very much!

Michael Orlitzky

unread,
May 13, 2012, 1:44:20 PM5/13/12
to sage-s...@googlegroups.com
On 05/13/2012 12:50 PM, Lorenzo wrote:
> u = sqrt(43203735824841025516773866131535024)

We actually have a doctest confirming that it's awful =)

This would probably be an easy project.


Definition: u.round(self)
Source:
def round(self):
"""
Round this expression to the nearest integer.

This method evaluates an expression in ``RR`` first and rounds
the result. This may lead to misleading results.

EXAMPLES::

sage: t = sqrt(Integer('1'*1000)).round(); t
3333333333333333056287287783757109595393...

This is off by a huge margin::

sage: (Integer('1'*1000) - t^2).ndigits()
984
"""
#FIXME: can we do better?

Zimmermann Paul

unread,
May 14, 2012, 4:20:28 AM5/14/12
to sage-s...@googlegroups.com
Hi Lorenzo,

the strange behaviour of round() is explained in the documentation:

sage: u.round?
...
This method evaluates an expression in "RR" first and rounds the
result. This may lead to misleading results.

sage: RR(u).round()
207855083711803936
sage: RealField(100)(u).round()
207855083711803945

Paul Zimmermann

Daniel Krenn

unread,
May 18, 2012, 4:33:06 AM5/18/12
to sage-s...@googlegroups.com
This is now #12968. (I couldn't find a ticket for it, but the problem was documented in the source code (see other answers to that posting). Does someone know that there is a ticket for it already?)
Reply all
Reply to author
Forward
0 new messages