Ask Your Question
1

Request: Have the len function output a Sage Integer instead of a Python int

asked 2019-10-02 16:02:50 +0200

Adrian soto gravatar image

updated 2019-10-04 18:23:29 +0200

In the following code (See https://sagecell.sagemath.org/?q=cctcfj ):

a=[4,5,6]

b=[0,1,2]

for i in zip([0,1,2],a):

    print i[0],"divided by",len(a),"is equal to",i[0]/len(a)


a=[4,5,6]

b=range(len(a))

print(b)

for i in zip(b,a):

    print i[0],"divided by",len(a),"is equal to",i[0]/len(a)

Gives the following output

0 divided by 3 is equal to 0

1 divided by 3 is equal to 1/3

2 divided by 3 is equal to 2/3

[0, 1, 2]
0 divided by 3 is equal to 0

1 divided by 3 is equal to 0

2 divided by 3 is equal to 0

Greetings

-A

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-10-02 16:20:41 +0200

rburing gravatar image

updated 2019-10-04 08:41:13 +0200

In the second part you are using Python ints instead of SageMath Integers.

Use srange (with universe=ZZ if you're not passing an Integer) instead of range, or convert to an Integer before the division, e.g. Integer(i[0])/len(a).

edit flag offensive delete link more

Comments

I think python int's should be converted to sage's; but it is a good workaround. I still think it is a bug.

Adrian soto gravatar imageAdrian soto ( 2019-10-03 00:37:53 +0200 )edit

It is not a bug. One should be aware of the difference between int and Integer. The second part of your code uses int division, there is no magic Sage can do to change that. Just be careful to write srange when you want Integers.

rburing gravatar imagerburing ( 2019-10-03 07:02:21 +0200 )edit
1

Thank you very much for the clarifications, the quick response, and for the suggestions, which solved the problems in the code I had.

However, the same behaviour occurs if I change range by srange. The problem seems to be that zip reverts sage Integer to Python int.

See https://sagecell.sagemath.org/?q=iyqcsn

Is that intended?

Adrian soto gravatar imageAdrian soto ( 2019-10-04 06:00:55 +0200 )edit

Ah, there is a subtlety with srange (explained in the documentation) that by default the output consists of numbers of the type you put in. You can override that by passing universe=ZZ to srange; I've added this to the answer.

rburing gravatar imagerburing ( 2019-10-04 08:45:45 +0200 )edit

As you can check, srange already had produced sage Integers, and not ints... so the problem is rather in the zip command, I think.

I will study how zip behaves a bit further.

Adrian soto gravatar imageAdrian soto ( 2019-10-04 17:19:00 +0200 )edit

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: 2019-10-02 16:02:50 +0200

Seen: 655 times

Last updated: Oct 04 '19