Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers?

Note that Python uses “unlimited” integers, but in numpy everything is typed, and so it is a “C”-style (probably 64-bit) integer here. You’re probably experiencing an overflow.

If you look at the documentation for numpy.prod, you can see the dtype parameter:

The type of the returned array, as well as of the accumulator in which the elements are multiplied.

There are a few things you can do:

  1. Drop back to Python, and multiply using its “unlimited integers” (see this question for how to do so).

  2. Consider whether you actually need to find the product of such huge numbers. Often, when you’re working with the product of very small or very large numbers, you switch to sums of logarithms. As @WarrenWeckesser notes, this is obviously imprecise (it’s not like taking the exponent at the end will give you the exact solution) – rather, it’s used to gauge whether one product is growing faster than another.

Leave a Comment