Skip to content

Commit 4c49563

Browse files
committed
Add nextafter and nextafterf from musl
1 parent f43bc0d commit 4c49563

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

src/math/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ mod log2f;
146146
mod logf;
147147
mod modf;
148148
mod modff;
149+
mod nextafter;
150+
mod nextafterf;
149151
mod pow;
150152
mod powf;
151153
mod remainder;
@@ -258,6 +260,8 @@ pub use self::log2f::log2f;
258260
pub use self::logf::logf;
259261
pub use self::modf::modf;
260262
pub use self::modff::modff;
263+
pub use self::nextafter::nextafter;
264+
pub use self::nextafterf::nextafterf;
261265
pub use self::pow::pow;
262266
pub use self::powf::powf;
263267
pub use self::remainder::remainder;

src/math/nextafter.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#[inline]
2+
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
3+
pub fn nextafter(x: f64, y: f64) -> f64 {
4+
if x.is_nan() || y.is_nan() {
5+
return x + y;
6+
}
7+
8+
let mut ux_i = x.to_bits();
9+
let uy_i = y.to_bits();
10+
if ux_i == uy_i {
11+
return y;
12+
}
13+
14+
let ax = ux_i & !1_u64 / 2;
15+
let ay = uy_i & !1_u64 / 2;
16+
if ax == 0 {
17+
if ay == 0 {
18+
return y;
19+
}
20+
ux_i = (uy_i & 1_u64 << 63) | 1;
21+
} else if ax > ay || ((ux_i ^ uy_i) & 1_u64 << 63) != 0 {
22+
ux_i -= 1;
23+
} else {
24+
ux_i += 1;
25+
}
26+
27+
let e = ux_i.wrapping_shr(52 & 0x7ff);
28+
// raise overflow if ux.f is infinite and x is finite
29+
if e == 0x7ff {
30+
force_eval!(x + x);
31+
}
32+
let ux_f = f64::from_bits(ux_i);
33+
// raise underflow if ux.f is subnormal or zero
34+
if e == 0 {
35+
force_eval!(x * x + ux_f * ux_f);
36+
}
37+
ux_f
38+
}

src/math/nextafterf.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#[inline]
2+
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
3+
pub fn nextafterf(x: f32, y: f32) -> f32 {
4+
if x.is_nan() || y.is_nan() {
5+
return x + y;
6+
}
7+
8+
let mut ux_i = x.to_bits();
9+
let uy_i = y.to_bits();
10+
if ux_i == uy_i {
11+
return y;
12+
}
13+
14+
let ax = ux_i & 0x7fff_ffff_u32;
15+
let ay = uy_i & 0x7fff_ffff_u32;
16+
if ax == 0 {
17+
if ay == 0 {
18+
return y;
19+
}
20+
ux_i = (uy_i & 0x8000_0000_u32) | 1;
21+
} else if ax > ay || ((ux_i ^ uy_i) & 0x8000_0000_u32) != 0 {
22+
ux_i -= 1;
23+
} else {
24+
ux_i += 1;
25+
}
26+
27+
let e = ux_i.wrapping_shr(0x7f80_0000_u32);
28+
// raise overflow if ux_f is infinite and x is finite
29+
if e == 0x7f80_0000_u32 {
30+
force_eval!(x + x);
31+
}
32+
let ux_f = f32::from_bits(ux_i);
33+
// raise underflow if ux_f is subnormal or zero
34+
if e == 0 {
35+
force_eval!(x * x + ux_f * ux_f);
36+
}
37+
ux_f
38+
}

0 commit comments

Comments
 (0)