How to know if np.prod() output is within the dtype range?

Hello Everyone!

I’m a bit confused with how np.prod() works. I hope you can help.

I was wondering how to be sure if the output of np.prod() method will be within the range of the default dtype if no arguments given for dtype.

As you can see on my code below, if I do not specify that I want the dtype of my output to be float64, the output differs. When no arguments given for dtype argument, the output is 1 less.

Screen Link:
https://app.dataquest.io/m/1028/numpy-datatypes-practice-problems/10/floating-point-error

My Code:

import numpy as np
x = np.array([97.0, 257.0, 673.0], dtype=np.float32)

product1 = np.prod(x)
print(product1)

product2 = np.prod(x, dtype=np.float64)
print(product2)

What I expected to happen:

To get some kind of an error saying that the output is not within float32 range and I should specify float64 as dtype.

What actually happened:

16777216.0 
16777217.0

You can check here.
As we can see in the code
x = np.array([97.0, 257.0, 673.0], dtype=np.float32)
Hence, data type of array x is float32.

Since the array is of float32 type, if we don’t provide any dtype in np.prod(), the output will be of float32 type. You can inspect the output variables and see this yourself.
image

The code is programmatically correct, that’s why you won’t get any errors when you “Run Code”. But when you Submit Answer", you will get an error message:
image
Next, I changed your code, used product for product1 variable:
image

Hope it’s clear now?

1 Like

Thank you for your answer! As you said the code is programmatically correct but maybe there is a way to dynamically pick the correct dtype for the correct output. I’ll be reading the documentation and If I can find something I’d be sharing :vulcan_salute: