473,395 Members | 1,668 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

why the inconsistency?

I just installed Python 2.3 (upgrading from 2.1).

Version 2.3 is noticably faster and the automatic
conversion to long integers is very handy:
print 2**64 18446744073709551616
But if I want to know how many digits 2**64 has, I can't
just do
print len(2**64) Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: len() of unsized object

So instead, I did this
print len(`2**64`) 21

But the correct answer is 20, not 21. The reason the
answer is wrong
print `2**64`

18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?
Jul 18 '05 #1
13 1490
On 23 Sep 2003 18:04:33 -0700, mensanator wrote:
print len(`2**64`) 21

But the correct answer is 20, not 21. The reason the
answer is wrong
print `2**64`

18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?


You want to perform two operations; make them explicit.

# Convert number to string representation
foo = "%d" % ( 2**64 )
# Get length of string
print len( foo )

As you've pointed out, a number has no inherent string representation
(and thus no length); choose one explicitly (e.g. by string formatting).

--
\ "I bought a dog the other day. I named him Stay. It's fun to |
`\ call him. 'Come here, Stay! Come here, Stay!' He went insane. |
_o__) Now he just ignores me and keeps typing." -- Steven Wright |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #2
On 23 Sep 2003 18:04:33 -0700, mensanator wrote:
print `2**64`

18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?


To answer this directly: because you've asked for the result of

repr( 2**64 )

which, as demonstrated, is showing you that the number is stored as a
long integer (since the point of repr() is to show you information about
the type of the object as well as its value).

I believe the `foo` syntax is deprecated in favour of repr( foo ), no?
If you'd used repr(), perhaps the assumption would have become
apparent.

--
\ "Outside of a dog, a book is man's best friend. Inside of a |
`\ dog, it's too dark to read." -- Groucho Marx |
_o__) |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #3

"mensanator" <me********@aol.com> wrote in message
news:fb**************************@posting.google.c om...
I just installed Python 2.3 (upgrading from 2.1).

Version 2.3 is noticably faster and the automatic
conversion to long integers is very handy:
print 2**64 18446744073709551616
But if I want to know how many digits 2**64 has, I can't
just do
print len(2**64) Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: len() of unsized object

So instead, I did this
print len(`2**64`) 21

But the correct answer is 20, not 21. The reason the
answer is wrong
print `2**64`

18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?


I believe it's scheduled to vanish in 2.4, but I could
be wrong about that.

John Roth
Jul 18 '05 #4
On Tue, Sep 23, 2003 at 06:04:33PM -0700, mensanator wrote:
I just installed Python 2.3 (upgrading from 2.1).

Version 2.3 is noticably faster and the automatic
conversion to long integers is very handy:
print 2**64 18446744073709551616
But if I want to know how many digits 2**64 has, I can't
just do
print len(2**64) Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: len() of unsized object

So instead, I did this
print len(`2**64`) 21

But the correct answer is 20, not 21. The reason the
answer is wrong
print `2**64` 18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?


I believe the L is there because the backticks invoke __repr__
intsead of __str__. I think backticks are somewhat deprecated
now. (At least Guido called them "a failed feature which never
got retired".)

I think what you want is 'str'.
a = 2**64
repr(a) '18446744073709551616L' str(a) '18446744073709551616' len(str(a)) 20


-John
--
<my first name>@<my domain>

Jul 18 '05 #5
On 23 Sep 2003 18:04:33 -0700, rumours say that me********@aol.com
(mensanator) might have written:

[snipped]
But if I want to know how many digits 2**64 has, I can't
just do


If only math.log(2**64)/math.log(10) worked with longs without
converting them into floats first... :(
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #6
On Wed, 24 Sep 2003 19:26:41 +0300, rumours say that Christos "TZOTZIOY"
Georgiou <tz**@sil-tec.gr> might have written:
If only math.log(2**64)/math.log(10) worked with longs without
converting them into floats first... :(


And after reading the FM, if only

def count_digits(x):
return int(math.log(x, 10))

worked correctly for *all* large values, like 10**70...
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #7
John Hazen <in*****@hazen.net> wrote in message news:<ma**********************************@python. org>...
On Tue, Sep 23, 2003 at 06:04:33PM -0700, mensanator wrote:
I just installed Python 2.3 (upgrading from 2.1).

Version 2.3 is noticably faster and the automatic
conversion to long integers is very handy:
>> print 2**64

18446744073709551616
But if I want to know how many digits 2**64 has, I can't
just do
>> print len(2**64)

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: len() of unsized object

So instead, I did this
>> print len(`2**64`)

21

But the correct answer is 20, not 21. The reason the
answer is wrong
>> print `2**64`

18446744073709551616L

Why is the "L" there? I thought "L" isn't used anymore?


I believe the L is there because the backticks invoke __repr__
intsead of __str__. I think backticks are somewhat deprecated
now. (At least Guido called them "a failed feature which never
got retired".)

I think what you want is 'str'.
a = 2**64
repr(a) '18446744073709551616L' str(a) '18446744073709551616' len(str(a)) 20


-John

Thanks to all who replied, it was very informative and helpfull. All
this is mentioned (including the discouraged use of backticks) in the
2.3 Tutorial Manual. Who knew you had to do the tutorial again?

In looking at this, I noticed that str() is EXTREMELY slow when
converting long integers to strings. Calculating f=150001! only took
about 10 minutes, but len(str(f)) took about an hour (for 711278
digits).

Lesson here is that

print len(str(f)),f

will do the string conversion twice, whereas

foo = str(f)
print len(foo),foo

will only do it once, which is handy to know when working with really
big numbers.

Thanks again.
Jul 18 '05 #8
Christos "TZOTZIOY" Georgiou <tz**@sil-tec.gr> writes:
On Wed, 24 Sep 2003 19:26:41 +0300, rumours say that Christos "TZOTZIOY"
Georgiou <tz**@sil-tec.gr> might have written:
If only math.log(2**64)/math.log(10) worked with longs without
converting them into floats first... :(


And after reading the FM, if only

def count_digits(x):
return int(math.log(x, 10))

worked correctly for *all* large values, like 10**70...


Um, it does :-)
float(40**200) Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: long int too large to convert to float math.log(40**200, 14)

279.56038792470861

(10**70 is well within the range of an IEEE double).

Cheers,
mwh

--
I really hope there's a catastrophic bug insome future e-mail
program where if you try and send an attachment it cancels your
ISP account, deletes your harddrive, and pisses in your coffee
-- Adam Rixey
Jul 18 '05 #9
Christos TZOTZIOY Georgiou wrote:
On 23 Sep 2003 18:04:33 -0700, rumours say that me********@aol.com
(mensanator) might have written:

[snipped]
But if I want to know how many digits 2**64 has, I can't
just do


If only math.log(2**64)/math.log(10) worked with longs without
converting them into floats first... :(


I'm not sure how you'd compute log on integer numbers. Anyway,
if you're in a hurry to know the number of digits in 2**64 -- I
see math.log(x,10) taking about 4 usec per loop, len(str(x)) about
6.3, in each case with x=2*64 and measuring with timeit.py
(elapsed time, as I'm measuring on Linux).

gmpy.numdigits(x) repeatably takes a bit less than 2 usec per loop;
if you're interested in speedy computations with "multi-precision"
values (integers, rationals, OR floats), you could do worse than
looking into gmpy (plug, plug;-).

(Note: all times measured on my old Athlon -- I did choose an Ahtlon,
back about 30 months ago, exactly because I had seen benchmarks where
it outperformed Intel CPU's by a mile on multi-precision integral
computations, particularly with the GMP library...).
Alex

Jul 18 '05 #10

"Alex Martelli" <al***@aleax.it> wrote in message news:Cx**********************@news2.tin.it...
I'm not sure how you'd compute log on integer numbers. Anyway,
if you're in a hurry to know the number of digits in 2**64 -- I
see math.log(x,10) taking about 4 usec per loop, len(str(x)) about
6.3, in each case with x=2*64 and measuring with timeit.py
(elapsed time, as I'm measuring on Linux).


And if you're really in a hurry 64 * log10(2) is good too ;)
Jul 18 '05 #11
Richard Brodie wrote:

"Alex Martelli" <al***@aleax.it> wrote in message
news:Cx**********************@news2.tin.it...
I'm not sure how you'd compute log on integer numbers. Anyway,
if you're in a hurry to know the number of digits in 2**64 -- I
see math.log(x,10) taking about 4 usec per loop, len(str(x)) about
6.3, in each case with x=2*64 and measuring with timeit.py
(elapsed time, as I'm measuring on Linux).


And if you're really in a hurry 64 * log10(2) is good too ;)


Yep, but it doesn't generalize to an 'x' computed elsewhere,
when all you know is that it's some big integer and need to
know how many digits its decimal representation will take.
Alex

Jul 18 '05 #12
Alex Martelli <al***@aleax.it> wrote:
I'm not sure how you'd compute log on integer numbers. Anyway,
if you're in a hurry to know the number of digits in 2**64 -- I
see math.log(x,10) taking about 4 usec per loop, len(str(x)) about
6.3, in each case with x=2*64 and measuring with timeit.py
(elapsed time, as I'm measuring on Linux).


And if you're really in a hurry 64 * log10(2) is good too ;)


Yep, but it doesn't generalize to an 'x' computed elsewhere,
when all you know is that it's some big integer and need to
know how many digits its decimal representation will take.


Some fast way of computing a tuple (bitmask,nbits) from a long integer
in Python can be interesting anyway, if only to facilitate bit
twiddling experiments. Below's a -probably buggy- part of a
C-extension I wrote some time ago. Now that the subject comes
reasonably close to it, maybe I can get a few stylistic hints about
this code.

Anton

static PyObject * truerand_longmask(PyObject *self, PyObject *args){
PyObject *argument, *result;
PyLongObject *v;
int i,size;
digit msd, mask, msdmask, bmask,*buffer;
if (!PyArg_ParseTuple(args, "O", &argument)){
return NULL;}
v = (PyLongObject *) PyNumber_Long(argument);
v = long_normalize(v);
size = ABS(v->ob_size);
msd = v->ob_digit[size-1];
Py_DECREF(v);
mask = BASE + MASK;
buffer = malloc(size * sizeof(digit));
for (i = size; --i >= 1;) buffer[i] = mask;
buffer[0] = 0;
result = _PyLong_FromByteArray((char *) buffer,
size * sizeof(digit),
0, /* little-endian */
0 /* signed */);
free(buffer);
v = (PyLongObject *) result;
v->ob_size = size;
bmask = BASE;
msdmask = mask;
while (msd < bmask){
msdmask ^= bmask;
bmask >>= 1;
}
v->ob_digit[size-1] = msdmask;
return Py_BuildValue("Ni",result,size);
}
Jul 18 '05 #13
Anton Vredegoor wrote:
...
Some fast way of computing a tuple (bitmask,nbits) from a long integer
in Python can be interesting anyway, if only to facilitate bit
twiddling experiments. Below's a -probably buggy- part of a


Sure, but I think gmpy already offers good and fast functions for all of
these needs. E.g., gmpy.numdigits(x, 2) for the number of bits, and
also getbit, setbit, lowbits, ...
Alex

Jul 18 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Rim | last post by:
Hi, With the great unification of types and classes, what will happen to the following identity inconsistency? >>> class myint(int): pass .... >>> a=int(1); b=int(1) >>> a is b 1
15
by: Roberto A. F. De Almeida | last post by:
I found that when using negative indices, the slice object passed to __getitem__ depends on the number of slices. An example to clarify: class a: def __getitem__(self, index): return index ...
46
by: Scott Chapman | last post by:
There seems to be an inconsistency here: Python 2.3.2 (#1, Oct 3 2003, 19:04:58) on linux2 >>> 1 == True True >>> 3 == True False >>> if 1: print "true" ....
11
by: Carlos Ribeiro | last post by:
Hi all, While writing a small program to help other poster at c.l.py, I found a small inconsistency between the handling of keyword parameters of string.split() and the split() method of...
2
by: Peter Clifton | last post by:
Hello all, I am very new to this subject and learning by example. I have a small inconsistency in an XML file when transformed using different processors. I was wondering if someone could shed...
3
by: Art Krumsee | last post by:
I have a console app that reads and parses the command line. The code originally read something like this: dim CmdLine as String = Command() if CmdLine.indexof("-trace") then 'tracing is...
6
by: August Karlstrom | last post by:
Hi What's the cause of the inconsistency between variable and parameter declarations in C? What's wrong with e.g. void f(int a, b; char c); August
10
AdrianH
by: AdrianH | last post by:
I've been using C++ for years, and I thought that I was quite competent with it, but today I just noticed that there is something of an inconsistency with calling a constructor. If you use a...
0
by: Neo Geshel | last post by:
I am experiencing an inconsistency with System.Net.Mail. I have a web form on a site. The form gets filled, and one copy gets sent to the recipient (info@domain.com). This works just fine. ...
6
by: Wouter | last post by:
Hey hi.... I get this weird inconsistency in Firefox using floats. I made this little demo of it wich u can find here: http://tweed.xs4all.nl/demo/fffloats/ Now the ? Question mark should...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.