Numpy float promotion inconsistency

Viewed 76

It is my understanding that in x = f() * g(), first f() executes, then g(), then results are multiplied, and only then assigned to x. Yet below seems to contradict this:

import numpy as np

print(np.sqrt(2).dtype)
print((np.array([1.], dtype='float32') * np.array([.5], dtype='float64')).dtype)
print((np.array([1.], dtype='float32') * np.sqrt(2)).dtype)
>>> float64
>>> float64
>>> float32

In all my prior experience, Numpy promoted to the greater dtype, but not here. Same behavior if we assign individual arrays and multiply afterwards. I imagine Numpy uses some hidden attribute besides dtype rather than overruling Python execution.

How's it work?

1 Answers

In the 2nd line:

print((np.array([1.], dtype='float32') * np.array([.5], dtype='float64')).dtype)

you are multiplying two arrays and hence it promotes the dtype (as you expect). However, in third line:

print((np.array([1.], dtype='float32') * np.sqrt(2)).dtype)

You are multiplying a scalar into an array and it preserves the array dtype. Note that if instead you replace the scalar with an array like this:

print((np.array([1.], dtype='float32') * np.sqrt([2])).dtype)

You will get float64 as you expect again.

Related