Quamer Nasim
Quamer Nasim

Reputation: 376

overflow encountered in long scalers while stress testing for maximum pair-wise product

I'm trying stress testing over the maximum pair-wise product algorithm, where the constraints are 2 <= n <= 2.10^5; 0 <= a1,...,an <= 2.10^5 where n is the length of the array and a1,a2,...,an is the element of list. When I'm running the code which is shown below, it's giving me an error saying overflow encountered in long scalers. This can be avoided in c using long long but how to avoid in python. please help.

MY CODE

# python3
import numpy as np

def max_pairwise_product(numbers):

    n = len(numbers)
    max_product = 0
    for first in range(n):
        for second in range(first + 1, n):
            max_product = max(max_product, (numbers[first] * numbers[second]))

    return max_product

def fast_max_pairwise_product(numbers):

    max_num = max(numbers)  
    numbers.remove(max_num)
    sec_max_num = max(numbers)
    max_product = max_num * sec_max_num

    return max_product

while(True):
    n = np.random.randint(0,1000) + 2
    print(n)
    vector = list(np.random.randint(0,1000000, n))
    print(vector)
    res1 = max_pairwise_product(vector)
    res2 = fast_max_pairwise_product(vector)
    if(res1 != res2):
        print('Wrong Answer', res1, ' ' , res2)
        break
    else:
        print()

ERROR

C:/Users/INTEL/Desktop/Algorithm Specialization/Algorithm toolbox/Week 1/week1_programming_challenges/2_maximum_pairwise_product/stress_test.py:11: RuntimeWarning: overflow encountered in long_scalars
  max_product = max(max_product, (numbers[first] * numbers[second]))
C:/Users/INTEL/Desktop/Algorithm Specialization/Algorithm toolbox/Week 1/week1_programming_challenges/2_maximum_pairwise_product/stress_test.py:23: RuntimeWarning: overflow encountered in long_scalars
  max_product = max_num * sec_max_num

Upvotes: 0

Views: 99

Answers (1)

Rens
Rens

Reputation: 513

The error you're getting has to do with your datatype, as is discussed in this similar question. I think the solution is to specify the datatype as a 64-bit datatype. You can do this when creating your vector:

vector = list(np.float64(np.random.randint(0,1000000, n)))

"np.float64" makes the code work for me. Does it still do what you intend to do? Otherwise you could also look at other 64-bit datatypes, such as "int64" and "uint64".

Upvotes: 1

Related Questions