From 490818851860fb257e23fe7aa0ee32eaffc4ba40 Mon Sep 17 00:00:00 2001 From: Arthur Carcano Date: Tue, 20 Aug 2024 18:41:42 +0200 Subject: [PATCH] Change neutral element of to neg_zero The neutral element used to be positive zero, but +0 + -0 = +0 so -0 seems better indicated. --- library/core/src/iter/traits/accum.rs | 4 +-- .../core/tests/num/float_iter_sum_identity.rs | 27 +++++++++++++++++++ library/core/tests/num/mod.rs | 1 + 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 library/core/tests/num/float_iter_sum_identity.rs diff --git a/library/core/src/iter/traits/accum.rs b/library/core/src/iter/traits/accum.rs index c97cd042ab4..5b7d95c2f65 100644 --- a/library/core/src/iter/traits/accum.rs +++ b/library/core/src/iter/traits/accum.rs @@ -104,7 +104,7 @@ macro_rules! float_sum_product { impl Sum for $a { fn sum>(iter: I) -> Self { iter.fold( - 0.0, + -0.0, #[rustc_inherit_overflow_checks] |a, b| a + b, ) @@ -126,7 +126,7 @@ fn product>(iter: I) -> Self { impl<'a> Sum<&'a $a> for $a { fn sum>(iter: I) -> Self { iter.fold( - 0.0, + -0.0, #[rustc_inherit_overflow_checks] |a, b| a + b, ) diff --git a/library/core/tests/num/float_iter_sum_identity.rs b/library/core/tests/num/float_iter_sum_identity.rs new file mode 100644 index 00000000000..6d3224522a8 --- /dev/null +++ b/library/core/tests/num/float_iter_sum_identity.rs @@ -0,0 +1,27 @@ +#[test] +fn f32_ref() { + let x: f32 = -0.0; + let still_x: f32 = [x].iter().sum(); + assert_eq!(1. / x, 1. / still_x) +} + +#[test] +fn f32_own() { + let x: f32 = -0.0; + let still_x: f32 = [x].into_iter().sum(); + assert_eq!(1. / x, 1. / still_x) +} + +#[test] +fn f64_ref() { + let x: f64 = -0.0; + let still_x: f64 = [x].iter().sum(); + assert_eq!(1. / x, 1. / still_x) +} + +#[test] +fn f64_own() { + let x: f64 = -0.0; + let still_x: f64 = [x].into_iter().sum(); + assert_eq!(1. / x, 1. / still_x) +} diff --git a/library/core/tests/num/mod.rs b/library/core/tests/num/mod.rs index 9d2912c4b22..53ff5ab1ced 100644 --- a/library/core/tests/num/mod.rs +++ b/library/core/tests/num/mod.rs @@ -30,6 +30,7 @@ mod ops; mod wrapping; +mod float_iter_sum_identity; mod ieee754; mod nan;