-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
BUG: np.polyval
returns float64 for float32 coefficients
#26484
Comments
This function is quite simple. The error occurs at p = NX.asarray(p)
if isinstance(x, poly1d):
y = 0
else:
x = NX.asanyarray(x)
y = NX.zeros_like(x)
for pv in p:
y = y * x + pv
return y One possible solution would be to test if p = NX.asarray(p)
if isinstance(x, poly1d):
y = 0
elif isinstance(x, ndarray): # Preserve dtypes for NEP 50
x = NX.asanyarray(x, dtype=x.dtype)
y = NX.zeros_like(x, dtype=x.dtype)
else:
x = NX.asanyarray(x)
y = NX.zeros_like(x)
for pv in p:
y = y * x + pv
return y Or maybe |
Maybe something like:
Note how I'm getting the |
The best thing is probably to try to not convert things, the using |
As seberg already noted, using
will give incorrect results for something like This works on the cases I tested so far:
@luxedo Would you like to make a PR see whether this works? |
That's right! I was testing opposite condition. I tested a bit and the return value had the correct dtype but returned an array, so I just expanded the condition with the new types (float, int, complex) to keep the return consistent. I'm sending the PR right now. p = NX.asarray(p)
if isinstance(x, (poly1d, float, int, complex)):
y = 0
else:
x = NX.asanyarray(x)
y = NX.zeros_like(x)
for pv in p:
y = y * x + pv
return y >>> np.polyval(np.array([5.], dtype=np.float32), 5) # Suggestion
array([5.], dtype=float32) # Returns an array<float32>
>>> np.polyval(np.array([5.], dtype=np.float32), 5) # PR
np.float32(5.0) # Returns np.float32 |
The same issues occurs with the
@seberg As the expert on NEP 50, if possible this should also be fixed right? |
There might be some more cases. For example
|
Yeah, sounds right, although not sure we should backport them. Not sure I am understanding the first one, |
I checked a bit more:
This is easy to fix: inside
with
(which, as a nice bonus, is also faster) Another case:
To fix that, we need to have some special cases to check whether one of the input arguments is a scalar. One could also argue that |
np.polyval
returns float64 for float32 coefficientsnp.polyval
returns float64 for float32 coefficients
Describe the issue:
Under NEP 50, I'd expect that
np.polyval
with single precision coefficients and a scalar evaluation value preserves single precision, but it converts to float64 instead.Reproduce the code example:
Error message:
No response
Python and NumPy Versions:
Runtime Environment:
No response
Context for the issue:
No response
The text was updated successfully, but these errors were encountered: