Ask Your Question
1

Why is sage behaving weird when rounding rational numbers?

asked 8 years ago

con-f-use gravatar image

I might be doing something stupid, but Sage's int() and round() functions seem to be buggy to me.

I'm trying to use these with rational numbers to round towards zero. I'd expect -7/4 to round to -1 and +7/4 to round to 1. Instead I get different behavior for rationals and their decimal representation:

┌────────────────────────────────────────────────────────────────────┐
 SageMath Version 7.1, Release Date: 2016-03-20                     
 Type "notebook()" for the browser-based notebook interface.        
 Type "help()" for help.                                            
└────────────────────────────────────────────────────────────────────┘
sage: int(-1.75)              # Correctly rounds towards zero
-1
sage: int(-7/4)               # Does not round towards zero
-2
sage: (-7/4).round("toward")  # Does not round towards zero (despite what the documentation claims!)
-2
sage: -7/4 + 0.0              # The numbers are in fact the same!
-1.75

How do I round rational numbers towards zero in Sage?

Preview: (hide)

Comments

1

Try to read

t=3/2
t.round?
FrédéricC gravatar imageFrédéricC ( 8 years ago )

Also, you may wish to use ceil or floor for your application.

calc314 gravatar imagecalc314 ( 8 years ago )

1 Answer

Sort by » oldest newest most voted
2

answered 8 years ago

updated 8 years ago

I just tested int(-7/4) on sagecell.sagemath.org and it returns -1 as expected. This server is now running Sage 7.2, so perhaps there is an issue in 7.1.

The .round() option only applies to half integers, as indicated in the documentation. For example, (-3/2).round("toward") returns -1 while (-3/2).round("away") returns -2.

As suggested by @calc314, here is a function that rounds toward zero:

def f(x):
    if x > 0:
        return floor(x)
    else:
        return ceil(x)
Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

1 follower

Stats

Asked: 8 years ago

Seen: 1,177 times

Last updated: May 21 '16