From 8fe108796d9674bb828023539089b6e0636d9ea1 Mon Sep 17 00:00:00 2001 From: Christian Date: Fri, 29 Mar 2019 16:22:26 +0100 Subject: [PATCH 1/3] Added documentation on the remainder (Rem) operator for floating points. --- src/libcore/ops/arith.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/libcore/ops/arith.rs b/src/libcore/ops/arith.rs index 0252edee23125..007a8db6c47e7 100644 --- a/src/libcore/ops/arith.rs +++ b/src/libcore/ops/arith.rs @@ -537,6 +537,10 @@ rem_impl_integer! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } macro_rules! rem_impl_float { ($($t:ty)*) => ($( + + /// The remainder from the division of two floats. + /// + /// The remainder has the same sign as the dividend. For example: `-5.0 % 2.0 = -1.0`. #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; From ea369cbc2f733568779215fd2aa68a54d5b75327 Mon Sep 17 00:00:00 2001 From: Christian Date: Sat, 30 Mar 2019 10:03:47 +0100 Subject: [PATCH 2/3] Added an example that shows how the remainder function on floating point values is computed internally. --- src/libcore/ops/arith.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/libcore/ops/arith.rs b/src/libcore/ops/arith.rs index 007a8db6c47e7..484461687e4eb 100644 --- a/src/libcore/ops/arith.rs +++ b/src/libcore/ops/arith.rs @@ -540,7 +540,17 @@ macro_rules! rem_impl_float { /// The remainder from the division of two floats. /// - /// The remainder has the same sign as the dividend. For example: `-5.0 % 2.0 = -1.0`. + /// The remainder has the same sign as the dividend and is computed as: + /// `x - (x / y).trunc() * y`. + /// + /// # Examples + /// ``` + /// let x: f32 = 4.0; + /// let y: f32 = 2.5; + /// let remainder = x - (x / y).trunc() * y; + /// + /// assert_eq!(x % y, remainder); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; From a1c79056e5df1236a82bdc6b315660f93ed5b11e Mon Sep 17 00:00:00 2001 From: Christian Date: Mon, 1 Apr 2019 22:49:14 +0200 Subject: [PATCH 3/3] Improved the example with numbers that can be exactly represented as floats and added a comment with the solution. --- src/libcore/ops/arith.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libcore/ops/arith.rs b/src/libcore/ops/arith.rs index 484461687e4eb..77c2dfa51bbbf 100644 --- a/src/libcore/ops/arith.rs +++ b/src/libcore/ops/arith.rs @@ -545,10 +545,11 @@ macro_rules! rem_impl_float { /// /// # Examples /// ``` - /// let x: f32 = 4.0; - /// let y: f32 = 2.5; + /// let x: f32 = 50.50; + /// let y: f32 = 8.125; /// let remainder = x - (x / y).trunc() * y; /// + /// // The answer to both operations is 1.75 /// assert_eq!(x % y, remainder); /// ``` #[stable(feature = "rust1", since = "1.0.0")]