Skip to content

Commit

Permalink
auto merge of #18174 : huonw/rust/fix-sqrt, r=alexcrichton
Browse files Browse the repository at this point in the history
Closes #9987.
  • Loading branch information
bors committed Oct 20, 2014
2 parents 045bc28 + a1d5cd2 commit ddfe24d
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/libcore/num/f32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,11 @@ impl Float for f32 {

#[inline]
fn sqrt(self) -> f32 {
unsafe { intrinsics::sqrtf32(self) }
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf32(self) }
}
}

#[inline]
Expand Down
7 changes: 5 additions & 2 deletions src/libcore/num/f64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ impl Float for f64 {

#[inline]
fn sqrt(self) -> f64 {
unsafe { intrinsics::sqrtf64(self) }
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}

#[inline]
Expand Down Expand Up @@ -377,4 +381,3 @@ impl Float for f64 {
self * (value / 180.0)
}
}

2 changes: 2 additions & 0 deletions src/libcore/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1501,6 +1501,8 @@ pub trait Float: Signed + Primitive {
fn frac_1_sqrt2() -> Self;

/// Take the square root of a number.
///
/// Returns NaN if `self` is not a non-negative number.
fn sqrt(self) -> Self;
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
fn rsqrt(self) -> Self;
Expand Down
11 changes: 11 additions & 0 deletions src/libstd/num/f32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -787,4 +787,15 @@ mod tests {
assert_eq!(NEG_INFINITY.integer_decode(), (8388608u64, 105i16, -1i8));
assert_eq!(NAN.integer_decode(), (12582912u64, 105i16, 1i8));
}

#[test]
fn test_sqrt_domain() {
assert!(NAN.sqrt().is_nan());
assert!(NEG_INFINITY.sqrt().is_nan());
assert!((-1.0f32).sqrt().is_nan());
assert_eq!((-0.0f32).sqrt(), -0.0);
assert_eq!(0.0f32.sqrt(), 0.0);
assert_eq!(1.0f32.sqrt(), 1.0);
assert_eq!(INFINITY.sqrt(), INFINITY);
}
}
11 changes: 11 additions & 0 deletions src/libstd/num/f64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -789,4 +789,15 @@ mod tests {
assert_eq!(NEG_INFINITY.integer_decode(), (4503599627370496, 972, -1));
assert_eq!(NAN.integer_decode(), (6755399441055744u64, 972i16, 1i8));
}

#[test]
fn test_sqrt_domain() {
assert!(NAN.sqrt().is_nan());
assert!(NEG_INFINITY.sqrt().is_nan());
assert!((-1.0f64).sqrt().is_nan());
assert_eq!((-0.0f64).sqrt(), -0.0);
assert_eq!(0.0f64.sqrt(), 0.0);
assert_eq!(1.0f64.sqrt(), 1.0);
assert_eq!(INFINITY.sqrt(), INFINITY);
}
}

0 comments on commit ddfe24d

Please sign in to comment.