Skip to content

Commit ddfe24d

Browse files
committed
auto merge of #18174 : huonw/rust/fix-sqrt, r=alexcrichton
Closes #9987.
2 parents 045bc28 + a1d5cd2 commit ddfe24d

File tree

5 files changed

+34
-3
lines changed

5 files changed

+34
-3
lines changed

src/libcore/num/f32.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,11 @@ impl Float for f32 {
259259

260260
#[inline]
261261
fn sqrt(self) -> f32 {
262-
unsafe { intrinsics::sqrtf32(self) }
262+
if self < 0.0 {
263+
NAN
264+
} else {
265+
unsafe { intrinsics::sqrtf32(self) }
266+
}
263267
}
264268

265269
#[inline]

src/libcore/num/f64.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,11 @@ impl Float for f64 {
266266

267267
#[inline]
268268
fn sqrt(self) -> f64 {
269-
unsafe { intrinsics::sqrtf64(self) }
269+
if self < 0.0 {
270+
NAN
271+
} else {
272+
unsafe { intrinsics::sqrtf64(self) }
273+
}
270274
}
271275

272276
#[inline]
@@ -377,4 +381,3 @@ impl Float for f64 {
377381
self * (value / 180.0)
378382
}
379383
}
380-

src/libcore/num/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1501,6 +1501,8 @@ pub trait Float: Signed + Primitive {
15011501
fn frac_1_sqrt2() -> Self;
15021502

15031503
/// Take the square root of a number.
1504+
///
1505+
/// Returns NaN if `self` is not a non-negative number.
15041506
fn sqrt(self) -> Self;
15051507
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
15061508
fn rsqrt(self) -> Self;

src/libstd/num/f32.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -787,4 +787,15 @@ mod tests {
787787
assert_eq!(NEG_INFINITY.integer_decode(), (8388608u64, 105i16, -1i8));
788788
assert_eq!(NAN.integer_decode(), (12582912u64, 105i16, 1i8));
789789
}
790+
791+
#[test]
792+
fn test_sqrt_domain() {
793+
assert!(NAN.sqrt().is_nan());
794+
assert!(NEG_INFINITY.sqrt().is_nan());
795+
assert!((-1.0f32).sqrt().is_nan());
796+
assert_eq!((-0.0f32).sqrt(), -0.0);
797+
assert_eq!(0.0f32.sqrt(), 0.0);
798+
assert_eq!(1.0f32.sqrt(), 1.0);
799+
assert_eq!(INFINITY.sqrt(), INFINITY);
800+
}
790801
}

src/libstd/num/f64.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,4 +789,15 @@ mod tests {
789789
assert_eq!(NEG_INFINITY.integer_decode(), (4503599627370496, 972, -1));
790790
assert_eq!(NAN.integer_decode(), (6755399441055744u64, 972i16, 1i8));
791791
}
792+
793+
#[test]
794+
fn test_sqrt_domain() {
795+
assert!(NAN.sqrt().is_nan());
796+
assert!(NEG_INFINITY.sqrt().is_nan());
797+
assert!((-1.0f64).sqrt().is_nan());
798+
assert_eq!((-0.0f64).sqrt(), -0.0);
799+
assert_eq!(0.0f64.sqrt(), 0.0);
800+
assert_eq!(1.0f64.sqrt(), 1.0);
801+
assert_eq!(INFINITY.sqrt(), INFINITY);
802+
}
792803
}

0 commit comments

Comments
 (0)