Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52462
| Date | 2013-08-13 16:33 +0100 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: Question about function failing with large number |
| References | <520A2295.5040605@gmail.com> <CAPTjJmp3UnLpHwkg3xnHHYdj+GFmATi6FatZh=0KOez2OK5Hqw@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.538.1376408037.1251.python-list@python.org> (permalink) |
On 13/08/2013 13:42, Chris Angelico wrote:
> On Tue, Aug 13, 2013 at 1:12 PM, Anthony Papillion <papillion@gmail.com> wrote:
>> So I'm using the function below to test a large (617 digit) number for
>> primality. For some reason, when I execute the code, I get an error
>> telling me:
>>
>> OverflowError: long int too large to convert to float
>>
>> The error is being thrown on this line:
>>
>> for x in range(3, int(n**0.5)+1, 2):
>
> Python's integers are unbounded, storing arbitrary precision. Python's
> floats are limited to the range of the underlying IEEE implementation.
> You'll have a certain cutoff above which your system bombs.
>
>>>> float(1<<1023)
> 8.98846567431158e+307
>>>> float(1<<1024)
> Traceback (most recent call last):
> File "<pyshell#68>", line 1, in <module>
> float(1<<1024)
> OverflowError: long int too large to convert to float
>
> (The exact cutoff may depend on how your Python is built, I think;
> that was running on a 32-bit Python on Windows.)
>
[snip]
Here's a way to calculate the integer square root:
def int_sqrt(number):
root = 1
while True:
new_root = (root + number // root) // 2
if new_root == root:
break
root = new_root
return root
It's result is the largest integer whose square doesn't exceed the
original number.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Question about function failing with large number MRAB <python@mrabarnett.plus.com> - 2013-08-13 16:33 +0100
csiph-web