Ask Your Question
1

Integer result for fraction

asked 2016-01-27 13:12:43 -0500

Arnaud1418 gravatar image

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 flag offensive close merge delete

Comments

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 09:19:18 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-01-28 09:02:28 -0500

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
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'>]
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

Stats

Asked: 2016-01-27 13:12:43 -0500

Seen: 157 times

Last updated: Jan 28 '16