Ask Your Question

Rounding problems in sagetex. Sometimes

asked 2012-06-24 23:24:50 +0200

dazedANDconfused gravatar image

I was getting wrong answers with Sage. It came down to this:

c = randint(14,20)
d = randint(5,10)
$\frac{\sage{c}}{\sage{d}}-\frac{\sage{c-3}}{\sage{d+1}}=$ \\

When I compiled with the commented out line I got the wrong answer, so I commented it out and broke it down into the 3 calculations below it. Output is below: for 20/7 - 17/8, Sage calculates 20/7 as 2 (rounding down) but 17/8 as 17/8 (not rounding down) to get a final answer of 2-17/8=-1/8. Image of output below. Why does it round (down) in one case and not in the others? What is the proper way to get the correct fractional answer?

image description

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2012-06-25 00:35:38 +0200

DSM gravatar image

updated 2012-06-25 00:36:11 +0200

This isn't a sagetex-related issue: it's because randint returns a Python int:

sage: c = randint(14, 20)
sage: d = randint(5, 10)
sage: c
sage: d
sage: type(c), type(d)
(<type 'int'>, <type 'int'>)

and division of Python ints is truncating:

sage: c / d

The reason that the second one behaves is because the 3 and 1 in c-3 and d+1 are Sage Integers, and operations involving them and Python ints produce Sage objects (Integers, Rationals, etc), so things work the way they should:

sage: (c-3)/(d+1)
sage: type(_)
<type 'sage.rings.rational.Rational'>

If you wrap the randint call in Integer, it should behave, although I can't do a sagetex test at the moment:

sage: c = Integer(randint(14, 20))
sage: c
sage: type(c), parent(c)
(<type 'sage.rings.integer.Integer'>, Integer Ring)
edit flag offensive delete link more


I tested it in sagetex and it works, Thanks! +1.

dazedANDconfused gravatar imagedazedANDconfused ( 2012-06-25 00:52:34 +0200 )edit

Hmm. At first I thought this should be fixed. But now I'm not so sure, since it calls the Python random stuff more or less directly. Worth raising on sage-devel?

kcrisman gravatar imagekcrisman ( 2012-06-25 12:44:47 +0200 )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


Asked: 2012-06-24 23:24:50 +0200

Seen: 430 times

Last updated: Jun 25 '12