Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A first trap is the following one, i somehow guess, that this was the reason for the question:

sage: for a in range(1,3):
....:     for b in range(4,6):
....:         print a, b, a/b
....:         
1 4 0
1 5 0
2 4 0
2 5 0

The reason for this is the fact that range builds a list of python integers, so the division is the plain division of integers, it delivers also an integer as result, this is the floor of the mathematically considered fraction $a/b$. To see the types:

sage: [ (a, type(a)) for a in range(1,3) ]
[(1, <type 'int'>), (2, <type 'int'>)]

So in order to get rational numbers, we have to tell sage to use sage specific objects. To get a "better list" suited for an immediate division, we may use instead one of the following solutions:

  • convert each a in range(1,3) to a sage integer, or to a sage rational number, i.e. use [ ZZ(a) for a in range(1,3) ] and/or [ QQ(a) for a in range(1,3) ] ,
  • use the sage interval [1..2] ,
  • use the sage range IntegerRange(1,3) .

And here are the lines of code doing the job the one or the other way:

sage: [ ZZ(a)/ZZ(b) for a in range(1,3) for b in range(4,6) ]
[1/4, 1/5, 1/2, 2/5]
sage: [ QQ(a)/QQ(b) for a in range(1,3) for b in range(4,6) ]
[1/4, 1/5, 1/2, 2/5]
sage: [ a/b for a in [1..2] for b in [4,5] ]
[1/4, 1/5, 1/2, 2/5]
sage: [ ZZ(a)/ZZ(b) for a in IntegerRange(1,3) for b in IntegerRange(4,6) ]
[1/4, 1/5, 1/2, 2/5]
sage: [ QQ(a)/QQ(b) for a in IntegerRange(1,3) for b in IntegerRange(4,6) ]
[1/4, 1/5, 1/2, 2/5]

The related answer. List comprehension also accepts a boolean condition (with and and or if more complicated). In our case:

[(x,y) for x in IntegerRange(1,10) for y in IntegerRange(1,10) if gcd(x,y)==1]

One may construct the last list also by generating all fractions, then passing to the list of the set of the list:

sage: L1 = [ x/y for x in IntegerRange(1,10) for y in IntegerRange(1,10) if gcd(x,y)==1]
sage: L2 = [ x/y for x in IntegerRange(1,10) for y in IntegerRange(1,10) ]
sage: L1.sort()
sage: L2 = list(set(L2))
sage: L2.sort()
sage: L1 == L2
True
sage: len(L1), len(L2)
(55, 55)

The one (or the other way) will list - after a small adaptation to two different ranges - all irreducible (resp. all possibly reducible) fractions with numerator and denominator in given ranges. (If the ranges start from the one, the two lists coincide.)