Rollup merge of #72486 - Ralith:asinh-fix, r=dtolnay

Fix asinh of negative values

Rust's current implementation of asinh has [large errors](https://www.wolframalpha.com/input/?i=arcsinh%28x%29%2C+ln%28x%2B%28x%5E2%2B1%29%5E0.5%29%2C+x+from+-67452095.07139316+to+0) in its negative range. ~These are (mostly) not numerical, but rather seem due to an incorrect implementation.~ This appears to be due to avoidable catastrophic cancellation.
[Playground before/after](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bd04ae6d86d06612e4e389a8b95d19ab).
[glibc uses](81dca813cc/sysdeps/ieee754/dbl-64/s_asinh.c (L56)) abs here.

Many thanks to @danieldeankon for finding this weird behavior, @jebrosen for diagnosing it, and @toasteater for identifying the probable implementation error!
This commit is contained in:
Ralf Jung 2020-06-19 08:55:59 +02:00 committed by GitHub
commit 99be102a6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 10 deletions

View File

@ -832,11 +832,7 @@ impl f32 {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asinh(self) -> f32 {
if self == Self::NEG_INFINITY {
Self::NEG_INFINITY
} else {
(self + ((self * self) + 1.0).sqrt()).ln().copysign(self)
}
(self.abs() + ((self * self) + 1.0).sqrt()).ln().copysign(self)
}
/// Inverse hyperbolic cosine function.
@ -1413,6 +1409,8 @@ mod tests {
assert!((-0.0f32).asinh().is_sign_negative()); // issue 63271
assert_approx_eq!(2.0f32.asinh(), 1.443635475178810342493276740273105f32);
assert_approx_eq!((-2.0f32).asinh(), -1.443635475178810342493276740273105f32);
// regression test for the catastrophic cancellation fixed in 72486
assert_approx_eq!((-3000.0f32).asinh(), -8.699514775987968673236893537700647f32);
}
#[test]

View File

@ -834,11 +834,7 @@ impl f64 {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asinh(self) -> f64 {
if self == Self::NEG_INFINITY {
Self::NEG_INFINITY
} else {
(self + ((self * self) + 1.0).sqrt()).ln().copysign(self)
}
(self.abs() + ((self * self) + 1.0).sqrt()).ln().copysign(self)
}
/// Inverse hyperbolic cosine function.
@ -1442,6 +1438,8 @@ mod tests {
// issue 63271
assert_approx_eq!(2.0f64.asinh(), 1.443635475178810342493276740273105f64);
assert_approx_eq!((-2.0f64).asinh(), -1.443635475178810342493276740273105f64);
// regression test for the catastrophic cancellation fixed in 72486
assert_approx_eq!((-67452098.07139316f64).asinh(), -18.72007542627454439398548429400083);
}
#[test]