Robert Frost
Robert Frost

Reputation: 119

Primorials in numpy - RuntimeWarning: overflow encountered in longlong_scalars

I've modified the following code from another post to quickly list the primes less than n in Python 3:

import numpy
def primesfrom2to(n):
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
    for i in range(1,int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[       k*k//3     ::2*k] = False
            sieve[k*(k-2*(i&1)+4)//3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

Then the following code is intended to generate a list of primes paired with their primorial (the product of all primes no greater than n), which it does to an extent:

def primorials2to(n):
#        primesfrom2ton=primesfrom2to(n)
        primorialpairs = [[1,1]]
        for prime in primesfrom2to(n):
#            print(prime)
#            print(primorial[-1])
            primorialpairs.append([prime,int(primorialpairs[-1][1]*prime)])
        return primorialpairs

It lists [1,1] which is of course not a [prime,primorial] pair, but that's fine it's done as a simple convenience to initiate the list as a list.

But the problem I have is that by [53,...] I experience the following error:

RuntimeWarning: overflow encountered in longlong_scalars

I suspect that I probably want to declare a 64 bit type in order to go large but have no idea how to do this. I've added int() to no avail.

Upvotes: 0

Views: 3160

Answers (1)

Denziloe
Denziloe

Reputation: 8152

The problem is that prime is a numpy number, which has a limited size. You're casting to int after the damage has been done by making a numpy number too large with primorialpairs[-1][1]*prime.

Python ints are of unlimited size. So a quick fix is to do everything with Python ints by inserting

prime = int(prime)

before the append.

Upvotes: 4

Related Questions