# Integer result for fraction

Hi!

Can somebody explain me this strange behavior of Sage :

for p in range(1,10):
for q in range(1,10):
print p/q


Then p/q return the integer division.

However:

for p in range(1,10):
print p/7


give rational results.

A solution is to use Rational(p)/Rational(q) instead of p/q. But it is not an explanation.

Thanks,

Arnaud

edit retag close merge delete

In working with Sage you have to know if you are dealing with a Sage integer or Python integer. They behave differently. Use srange as indicated in answer below. See also, this similar post

Sort by » oldest newest most voted

Ah! This is because range(1,10) is a pure Python command and so returns Python ints. Which, as we are using Python 2, return like this.

sage: preparser(False)
sage: 1/2
0
sage: preparser(True)
sage: 1/2
1/2


But once you use p/7, Sage's preparser says "That's the rational number p/7" and so does this correctly.

sage: preparse('p/7')
'p/Integer(7)'


A better solution is to use srange, which always uses Sage types if it can.

sage: srange(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
sage: [type(i) for i in srange(1,10)]
[<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>,
<type 'sage.rings.integer.Integer'>]

more