Ask Your Question
1

ratio of integers

asked 2013-08-14 08:01:23 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

the output of this

d=3
for n in range (1,d):
    print n,d,n/d

is correctly

1 3 1/3
2 3 2/3

on the other hand, the output of this

for d in range(2,4):
    for n in range(1,d):
        print n,d,n/d

is

1 2 0
1 3 0
2 3 0

why, in this case, is the ratio n/d always zero?

('Sage Version 5.10, Release Date: 2013-06-17', firefox 23.0, osx 10.6.8)

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
4

answered 2013-08-14 09:07:01 +0200

Nathann gravatar image

I would say that it is because

type(d)

does not return the same thing in the two cases. There are different forms of integers in Sage, and it can be tricky from time to time : there are for instance "python" integers (i.e. int(6)) and Sage integers (i.e. Integer(6)).

The range function, in particular, only returns Python integers

sage: int(9)/int(4)
2

While you probably want to use Sage integers instead, which knows when they should consider themselves as rational numbers

sage: Integer(9)/Integer(4)
9/4

Sooooooo if you want to change your code a bit, I would say that you can fix it by replacing {{{range(something)}}} by {{{srange(something)}}}. srange returns Sage integers :-)

sage: map(type,range(4))
[int, int, int, int]
sage: map(type,srange(4))
[sage.rings.integer.Integer,
 sage.rings.integer.Integer,
 sage.rings.integer.Integer,
 sage.rings.integer.Integer]

Nathann

edit flag offensive delete link more
0

answered 2013-08-14 09:20:22 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Using print n,d,type(n/d), I am seeing that in the first case, Sage treats the values in sage.rings.rational.Rational and so you get the output you want. In the second case, Sage treats the values as integers and so the division gives the integer quotient.

What I don't know is why Sage is making these particular interpretations in these cases. Perhaps others can give us an idea of why this is happening.

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

Stats

Asked: 2013-08-14 08:01:23 +0200

Seen: 847 times

Last updated: Aug 14 '13