The "range" function is a Python one, and it returns Python ints.
Python ints have truncating division, so that 3/2 = 1, not 3/2. When
you type 3/2 at the Sage command, it's preparsed to be Sage Integers:
sage: 3/2
3/2
sage: preparse("3/2")
'Integer(3)/Integer(2)'
sage: int(3)/int(2)
1
sage: 3r/2r
1
(I don't know what the "r" is supposed to stand for but I always think
of it as "raw", i.e. Python, not Sage. I might even be right.) So in
your code your C values are wrong in the second loop. They work in
the first loop because "B=-2" makes it a Sage Integer, and so the
results of divisions can become Rationals like you expect.
print 'Loop 2:'
for A in range(-3,-1):
for B in range(-3,-1):
Cint = -A*B/(A+B)
CInt = (1)*-A*B/(A+B)
print A, B,
print 'Cint:', Cint, A*B+Cint*(A+B),
print 'CInt:', CInt, A*B+CInt*(A+B)
gives:
-3 -3 Cint: 1 3 CInt: 3/2 0
-3 -2 Cint: 1 1 CInt: 6/5 0
-2 -3 Cint: 1 1 CInt: 6/5 0
-2 -2 Cint: 1 0 CInt: 1 0
The multiplication by the Sage Integer 1 makes the CInt expression a
Sage one, and so it works. For these reasons, I tend to avoid using
"range" in Sage code entirely. There are several
alternatives. There's srange/xsrange=sxrange
sage: srange(-3, -1)
[-3, -2]
sage: sxrange(-3, -1)
<generator object generic_xsrange at 0x10d57ae10>
sage: list(sxrange(-3, -1))
[-3, -2]
(The "s" stands for Sage):
Or you can be explicit and use IntegerRange, which gives a more
informative string:
sage: IntegerRange(-3, -1)
{-3, -2}
I like the "(a..b)" and "[a..b]" syntaxes myself:
sage: for A in (-3..-2): print A, type(A)
....:
-3 <type 'sage.rings.integer.Integer'>
-2 <type 'sage.rings.integer.Integer'>
but note that it includes the right hand limit. I find this is more
useful in mathematical code than in pure programming, mostly because I
often find cases where I want (a..a) to include a, but your mileage
may vary.
Does that make sense?
Doug
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org