Ask Your Question
0

Rounding problems in sagetex. Sometimes

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

dazedANDconfused gravatar image

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

\documentclass[12pt]{article}%
\usepackage{sagetex}
\begin{document}
\begin{sagesilent}
c = randint(14,20)
d = randint(5,10)
\end{sagesilent}
$\frac{\sage{c}}{\sage{d}}-\frac{\sage{c-3}}{\sage{d+1}}=$ \\
%$\sage{c/d-((c-3)/(d+1))}$\\
$\sage{c/d}$\\
$\sage{((c-3)/(d+1))}$\\
$\sage{c/d-((c-3)/(d+1))}$
\end{document}

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
3

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

DSM gravatar image

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

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
17
sage: d
7
sage: type(c), type(d)
(<type 'int'>, <type 'int'>)

and division of Python ints is truncating:

sage: c / d
2

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)
7/4
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
15
sage: type(c), parent(c)
(<type 'sage.rings.integer.Integer'>, Integer Ring)
edit flag offensive delete link more

Comments

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

dazedANDconfused gravatar imagedazedANDconfused ( 2012-06-25 00:52:34 +0100 )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 +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: 2012-06-24 23:24:50 +0100

Seen: 483 times

Last updated: Jun 25 '12