-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
ENH: special: fix premature overflow in boxcox
#20073
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
Conversation
Thanks @xuefeng-xu! Since this is modifying the formulation for all values (not just in cases of overflow), I'd like a |
The modified formulation loses precision when:
import mpmath
import numpy as np
from scipy.special._mptestutils import (
Arg, assert_mpmath_equal, exception_to_nan)
np.seterr(over='ignore')
def boxcox(x, lmbda):
if abs(lmbda) < 1e-14: # change 1e-19 to 1e-14
return np.log(x)
else:
# return np.expm1(lmbda * np.log(x)) / lmbda
return np.sign(lmbda) * np.exp(lmbda * np.log(x) - np.log(abs(lmbda))) - 1 / lmbda
def test_boxcox():
def mp_boxcox(x, lmbda):
x = mpmath.mp.mpf(x)
lmbda = mpmath.mp.mpf(lmbda)
if lmbda == 0:
return mpmath.mp.log(x)
else:
return mpmath.mp.powm1(x, lmbda) / lmbda
assert_mpmath_equal(
boxcox,
exception_to_nan(mp_boxcox),
[Arg(a=0, inclusive_a=False), Arg()],
n=1000,
dps=100,
rtol=1e-13,
)
print(boxcox(1, 10)) # -2.7755575615628914e-17 (not 0) |
Maybe we can use the same formula as the mpmath implementation using scipy's Another possibility would be to use the old formulation for small values and the new one for large ones. |
Thanks @mdhaber @dschmitz89 ! |
Thanks for your patience @xuefeng-xu. @steppi is a |
boxcox
Co-authored-by: Jake Bowhay <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks good to me.
Thanks @steppi @xuefeng-xu! |
Reference issue
#19604 (comment)
Towards #19016
What does this implement/fix?
Fix premature overflow of the following modules.
special.boxcox
,special.inv_boxcox
,special.boxcox1p
,special.inv_boxcox1p
Additional information