Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52462 > unrolled thread

Re: Question about function failing with large number

Started byMRAB <python@mrabarnett.plus.com>
First post2013-08-13 16:33 +0100
Last post2013-08-13 16:33 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Question about function failing with large number MRAB <python@mrabarnett.plus.com> - 2013-08-13 16:33 +0100

#52462 — Re: Question about function failing with large number

FromMRAB <python@mrabarnett.plus.com>
Date2013-08-13 16:33 +0100
SubjectRe: Question about function failing with large number
Message-ID<mailman.538.1376408037.1251.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web