about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-08-21 21:58:28 +0200
committerGitHub <noreply@github.com>2024-08-21 21:58:28 +0200
commit3fb8faa65380ed8f4b0376b2ebc0abba10f0dc0f (patch)
treeae51ad69d49fd15a7a4b833306c5a1b141805612
parent94b395385396c63155fda3ac9e309972ce3ea3e3 (diff)
parent490818851860fb257e23fe7aa0ee32eaffc4ba40 (diff)
downloadrust-3fb8faa65380ed8f4b0376b2ebc0abba10f0dc0f.tar.gz
rust-3fb8faa65380ed8f4b0376b2ebc0abba10f0dc0f.zip
Rollup merge of #129321 - krtab:float_sum, r=workingjubilee
Change neutral element of <fNN as iter::Sum> to neg_zero

The neutral element used to be positive zero, but +0 + -0 = +0 so -0 seems better indicated.
-rw-r--r--library/core/src/iter/traits/accum.rs4
-rw-r--r--library/core/tests/num/float_iter_sum_identity.rs27
-rw-r--r--library/core/tests/num/mod.rs1
3 files changed, 30 insertions, 2 deletions
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<I: Iterator<Item=Self>>(iter: I) -> Self {
                 iter.fold(
-                    0.0,
+                    -0.0,
                     #[rustc_inherit_overflow_checks]
                     |a, b| a + b,
                 )
@@ -126,7 +126,7 @@ macro_rules! float_sum_product {
         impl<'a> Sum<&'a $a> for $a {
             fn sum<I: Iterator<Item=&'a Self>>(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 int_log;
 mod ops;
 mod wrapping;
 
+mod float_iter_sum_identity;
 mod ieee754;
 mod nan;