# Integer types and log()

I am working with a bunch of lists whose lengths are all powers of 2. I'd like to be able to extract the power by taking the base-2 log of the length. However, Sage wasn't able to simplify an expression like log(len(L),2), because apparently len() returns the wrong kind of integer:

sage: A=list(range(8))
sage: len(A)
8
sage: log(len(A),2)
log(8)/log(2)
sage: log(8,2)
3
sage: type(len(A))
<type 'int'>
sage: type(8)
<type 'sage.rings.integer.Integer'>
sage: log(Integer(len(A)),2)
3


This is the first math function I've come across that seems to care about the distinction between these two kinds of integers, and it would be nice if it didn't, since it took me quite a while to figure out why Sage wouldn't simplify an expression like log(len(A),2).

edit retag close merge delete

This was fixed at some point (thanks!). In Sage 9.3:

sage: a, b = log(8, 2), log(int(8), 2)
sage: a, b
(3, 3)


Sort by » oldest newest most voted

To get the exponent in a number factor use valuation:

sage: valuation(8,2)
3
sage: valuation(65536,2)
16
sage: e=[None]*8
sage: valuation(len(e),2)
3


To get the numerical value of a symbolic expression like log(8)/log(2) use n():

sage: log(8)/log(2)
log(8)/log(2)
sage: N(log(8)/log(2))
3.00000000000000


This will be floating point however so better use the first method.

more

Thanks. I did not know about the valuation() function before this.

Could you please report this bug by sending a message to sage-devel ? You only need say that the following looks weird:

sage: log(int(8),2)
log(8)/log(2)
sage: log(8,2)
3


About your problem: you can easily solve it by explicitly turning len(A) into a Sage integer:

sage: e=[None]*8
sage: log(len(e),2)
log(8)/log(2)
sage: log(Integer(len(e)),2)
3

more

The reported behaviour is not a bug. Rather that your method works.

@Nathann: Done.

@rws: Yes, it is not a bug, and I was able to do what I needed to do, but from an end-user standpoint, it would be better if the log() function did not require the user to distinguish between an integer and a Sage integer - most mathematicians would not think that there could be two kinds of integers!

I guess Sage tries to hide most integers as Sage Integer objects, but there is no easy way to mess with the Python built-in len to have it return an Integer instead of a Python int without probably disturbing a lot of other stuff, unfortunately.