# Rounding problems in sagetex. Sometimes

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? edit retag close merge delete

Sort by » oldest newest most voted 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)

more

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?