0

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
Quamer Nasim
  • 366
  • 1
  • 5
  • 18
  • Does this answer your question? [Python RuntimeWarning: overflow encountered in long scalars](https://stackoverflow.com/questions/7559595/python-runtimewarning-overflow-encountered-in-long-scalars) – nice_dev Jan 16 '20 at 10:22

1 Answers1

1

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".

Rens
  • 473
  • 1
  • 3
  • 13
  • 1
    bro, but what if I don't want to use this np.float64 in stress test condition, what if I directly want to use this np.float64 in both the function which I've defined so that i can deploy my algorithm when I'm done testing. where to put this. please help me out with this – Quamer Nasim Jan 16 '20 at 10:45
  • I'm not sure if I understand the purpose of your script, but you can also use any other 64 bit data type, such as "int64" or "uint64". – Rens Jan 16 '20 at 11:01