0

I am trying to perform an element wise multiplication of numerous numpy arrays.

The implementation:-

mult = np.ones(len(single_arrays[0]))
for i in range(len(single_arrays)):
    mult *= single_arrays[i]

Most values in the each of the single arrays is between 0 and 1(some values are above 1), and the 2D "single_arrays" has about 700 individual arrays.

The resultant array "mult" has a lot of "inf" values and one "nan" value even though no array in the "single_arrays" has "inf" or "nan" values, all the values are valid floating points.

Why is this issue arising in mult ? Some values are very small in the array, going to tens and thousandths decimal places, could underflow or overflow be an issue here ?

StudentV
  • 57
  • 7
  • Based in this [question](https://stackoverflow.com/questions/34930570/at-what-point-should-i-worry-about-underflow-in-numpy-values) you can use [numpy.seterr](https://numpy.org/doc/stable/reference/generated/numpy.seterr.html) to raise an exception if underflow occurs. – StandardIO May 03 '23 at 02:47
  • Please provide us with `single_arrays` – Talha Tayyab May 03 '23 at 02:54

1 Answers1

1

If everything you said is correct, it can't happen. Therefore something you believe isn't true :-)

* can only deliver an infinity if a multiplicand is an inf, or the product is very large. But it can't be large if it's true that "all values in the each of the single arrays is between 0 and 1". Then no product can be larger than 1.0.

* can only deliver a NaN if a multiplicand is a NaN, or you try to multiply (in either order) an inf and a zero. Which you say you're never doing either.

Underflow is certainly possible, but is irrelevant - tiny numbers can't produce an inf unless you're dividing by a zero, or a very small number (close to 0, in the denormal range).

So add prints to find out what's actually happening. Pick an index j for which mult[j] ends up with an inf, then change the code to show you where it came from:

for i in range(len(single_arrays)):
    orig = mult[j]
    mult *= single_arrays[i]
    if mult[j] == inf:
        print("got an inf in mult[j]",
              "as the product of",
              orig, "and", single_arrays[i][j])
        assert False  # just a way to raise an exception

Try that and tell us what happens.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132