making unintendet floor division in Sage cloud

17 views
Skip to first unread message

Bassie

unread,
Apr 15, 2014, 7:53:11 PM4/15/14
to sage-s...@googlegroups.com
I'm running a double for loop, and dividing one over the other. Sagecloud converts these fractions to 0, just like python2, but isn't it exactly what it's not supposed to do.
"""
for d in range(1,8):
    for n in range(1,d):
        print n/d
0
0
0
0
0
0
0
0
etc.
"""

William Stein

unread,
Apr 15, 2014, 8:39:04 PM4/15/14
to sage-support
Sage only converts integer literals. You need to do

for d in [1..7]:
for n in [1..d-1]:
print n/d

or

for d in srange(1,8):
for n in srange(1,d):
print n/d


>
> --
> You received this message because you are subscribed to the Google Groups
> "sage-support" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sage-support...@googlegroups.com.
> To post to this group, send email to sage-s...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sage-support.
> For more options, visit https://groups.google.com/d/optout.



--
William Stein
Professor of Mathematics
University of Washington
http://wstein.org

kcrisman

unread,
Apr 15, 2014, 9:23:50 PM4/15/14
to sage-s...@googlegroups.com


On Tuesday, April 15, 2014 8:39:04 PM UTC-4, William wrote:
On Tue, Apr 15, 2014 at 4:53 PM, Bassie <thegra...@gmail.com> wrote:
> I'm running a double for loop, and dividing one over the other. Sagecloud
> converts these fractions to 0, just like python2, but isn't it exactly what
> it's not supposed to do.
> """
> for d in range(1,8):
>     for n in range(1,d):
>         print n/d
> 0
> 0
> 0
> 0
> 0
> 0
> 0
> 0
> etc.
> """

Sage only converts integer literals.  You need to do

for d in [1..7]:
    for n in [1..d-1]:
        print n/d


Just to make it clear, range(1,7) gives Python ints, while [1..7] gives Sage Integers.  srange ("Sage" range) would do the same thing.   Have fun!

for d in srange(1,8):
    for n in srange(1,d):
        print n/d

Jori Mantysalo

unread,
Apr 16, 2014, 2:16:31 AM4/16/14
to sage-s...@googlegroups.com
On Tue, 15 Apr 2014, kcrisman wrote:

>>> for d in range(1,8):
>>> for n in range(1,d):
>>> print n/d
>>> 0
>>> 0

> Just to make it clear, range(1,7) gives Python ints, while [1..7] gives
> Sage Integers.

In general one can also cast to right type and say

print Integer(n)/d

or

print 1*n/d

I guess there is no general setting to make all ints converted to
Integers? As an example

L1=[1,2]; L2=[1,2,3]; print len(L1)/len(L2)

also prints 0. So does "0+len(L1)/len(L2)", whereas again
"1*len(L1)/len(L2)" works as expected by most Sage users(?).

--
Jori Mäntysalo
Reply all
Reply to author
Forward
0 new messages