Ask Your Question

Integer result for fraction

asked 2016-01-27 20:12:43 +0200

Arnaud1418 gravatar image


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.


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.



edit retag flag offensive 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

dazedANDconfused gravatar imagedazedANDconfused ( 2016-01-28 16:19:18 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2016-01-28 16:02:28 +0200

kcrisman gravatar image

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
sage: preparser(True)
sage: 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')

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'>]
edit flag offensive delete link more

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


Asked: 2016-01-27 20:12:43 +0200

Seen: 409 times

Last updated: Jan 28 '16