1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Copyright © 2026 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate::InnerFloat::Finite;
use crate::{Float, significand_bits};
use malachite_base::num::arithmetic::traits::{NegAssign, PowerOf2};
use malachite_base::num::basic::traits::{Infinity, Zero};
use malachite_base::num::conversion::traits::WrappingFrom;
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_nz::natural::{Natural, bit_to_limb_count_floor};
use malachite_nz::platform::Limb;
impl Float {
/// Gets a [`Float`]'s ulp (unit in last place, or unit of least precision).
///
/// If the [`Float`] is positive, its ulp is the distance to the next-largest [`Float`] with the
/// same precision; if it is negative, the next-smallest. (This definition works even if the
/// [`Float`] is the largest in its binade. If the [`Float`] is the largest in its binade and
/// has the maximum exponent, we can define its ulp to be the distance to the next-smallest
/// [`Float`] with the same precision if positive, and to the next-largest [`Float`] with the
/// same precision if negative.)
///
/// If the [`Float`] is NaN, infinite, or zero, then `None` is returned.
///
/// This function does not overflow or underflow, technically. But it is possible that a
/// [`Float`]'s ulp is too small to represent, for example if the [`Float`] has the minimum
/// exponent and its precision is greater than 1, or if the precision is extremely large in
/// general. In such cases, `None` is returned.
///
/// $$
/// f(\text{NaN}) = f(\pm\infty) = f(\pm 0.0) = \text{None},
/// $$
///
/// and, if $x$ is finite and nonzero,
///
/// $$
/// f(x) = \operatorname{Some}(2^{\lfloor \log_2 |x| \rfloor-p+1}),
/// $$
/// where $p$ is the precision of $x$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::PowerOf2;
/// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeOne, One, Zero};
/// use malachite_float::Float;
///
/// assert_eq!(Float::NAN.ulp(), None);
/// assert_eq!(Float::INFINITY.ulp(), None);
/// assert_eq!(Float::ZERO.ulp(), None);
///
/// let s = Float::ONE.ulp().map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("1.0"));
///
/// let s = Float::one_prec(100).ulp().map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("1.6e-30"));
///
/// let s = Float::from(std::f64::consts::PI)
/// .ulp()
/// .map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("3.6e-15"));
///
/// let s = Float::power_of_2(100u64).ulp().map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("1.3e30"));
///
/// let s = Float::power_of_2(-100i64).ulp().map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("7.9e-31"));
///
/// let s = Float::NEGATIVE_ONE.ulp().map(|x| x.to_string());
/// assert_eq!(s.as_ref().map(|s| s.as_str()), Some("1.0"));
/// ```
pub fn ulp(&self) -> Option<Self> {
match self {
Self(Finite {
exponent,
precision,
..
}) => {
let ulp_exponent =
i64::from(*exponent).checked_sub(i64::try_from(*precision).ok()?)?;
if i32::try_from(ulp_exponent).ok()? >= Self::MIN_EXPONENT_MINUS_1 {
Some(Self::power_of_2(ulp_exponent))
} else {
None
}
}
_ => None,
}
}
/// Steps a [`Float`] up to the closest larger [`Float`] with the same precision. This matches
/// the IEEE 754 `nextUp` operation and MPFR's `mpfr_nextabove`, except that this function
/// panics on NaN, infinities, and zeros rather than handling them.
///
/// For most values this adds one ulp (see [`Float::ulp`]). If the [`Float`] is positive and is
/// the largest [`Float`] in its binade with its precision, then
/// - If its exponent is not the maximum exponent, it will become the power of 2 at the bottom
/// of the next-higher binade (still a step of one ulp);
/// - If its exponent is the maximum exponent, it will become $\infty$.
///
/// If the [`Float`] is negative and is closer to zero than any other [`Float`] in its binade
/// with its precision (that is, its significand is a power of 2), then
/// - If its exponent is not the minimum exponent, it will move half an ulp toward zero, to the
/// largest-magnitude [`Float`] in the next-lower binade with its precision (at precision 1
/// the next power of 2, at higher precisions the value with an all-ones significand);
/// - If its exponent is the minimum exponent, it will become negative zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `self` is NaN, infinite, or zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::PowerOf2;
/// use malachite_base::num::basic::traits::{NegativeOne, One};
/// use malachite_float::Float;
///
/// let mut x = Float::ONE;
/// assert_eq!(x.to_string(), "1.0");
/// x.increment();
/// assert_eq!(x.to_string(), "2.0");
///
/// let mut x = Float::one_prec(100);
/// assert_eq!(x.to_string(), "1.0000000000000000000000000000000");
/// x.increment();
/// assert_eq!(x.to_string(), "1.0000000000000000000000000000016");
///
/// let mut x = Float::from(std::f64::consts::PI);
/// assert_eq!(x.to_string(), "3.1415926535897931");
/// x.increment();
/// assert_eq!(x.to_string(), "3.1415926535897967");
///
/// let mut x = Float::power_of_2(100u64);
/// assert_eq!(x.to_string(), "1.3e30");
/// x.increment();
/// assert_eq!(x.to_string(), "2.5e30");
///
/// let mut x = Float::power_of_2(-100i64);
/// assert_eq!(x.to_string(), "7.9e-31");
/// x.increment();
/// assert_eq!(x.to_string(), "1.6e-30");
///
/// let mut x = Float::NEGATIVE_ONE;
/// assert_eq!(x.to_string(), "-1.0");
/// x.increment();
/// assert_eq!(x.to_string(), "-0.50");
/// ```
pub fn increment(&mut self) {
if self.is_sign_negative() {
self.neg_assign();
self.decrement();
self.neg_assign();
} else if let Self(Finite {
exponent,
precision,
significand,
..
}) = self
{
let ulp = Limb::power_of_2(significand_bits(significand) - *precision);
let limb_count = significand.limb_count();
significand.add_assign_at_limb(
usize::wrapping_from(limb_count) - 1 - bit_to_limb_count_floor(*precision - 1),
ulp,
);
if significand.limb_count() > limb_count {
// The value was the largest in its binade with its precision, so stepping up lands
// on the power of 2 at the bottom of the next-higher binade, which is representable
// with the same precision.
if *exponent == Self::MAX_EXPONENT {
*self = Self::INFINITY;
return;
}
*significand >>= 1u32;
*exponent += 1;
}
} else {
panic!("Cannot increment float is non-finite or zero");
}
}
/// Steps a [`Float`] down to the closest smaller [`Float`] with the same precision. This
/// matches the IEEE 754 `nextDown` operation and MPFR's `mpfr_nextbelow`, except that this
/// function panics on NaN, infinities, and zeros rather than handling them.
///
/// For most values this subtracts one ulp (see [`Float::ulp`]). If the [`Float`] is negative
/// and is the largest-magnitude [`Float`] in its binade with its precision, then
/// - If its exponent is not the maximum exponent, it will become the negative power of 2 at the
/// bottom of the next-higher binade (still a step of one ulp);
/// - If its exponent is the maximum exponent, it will become $-\infty$.
///
/// If the [`Float`] is positive and is smaller than any other [`Float`] in its binade with its
/// precision (that is, its significand is a power of 2), then
/// - If its exponent is not the minimum exponent, it will move half an ulp toward zero, to the
/// largest [`Float`] in the next-lower binade with its precision (at precision 1 the next
/// power of 2, at higher precisions the value with an all-ones significand);
/// - If its exponent is the minimum exponent, it will become positive zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `self` is NaN, infinite, or zero.
///
/// # Examples
/// ```
/// use malachite_base::num::arithmetic::traits::PowerOf2;
/// use malachite_base::num::basic::traits::{NegativeOne, One};
/// use malachite_float::Float;
///
/// let mut x = Float::ONE;
/// assert_eq!(x.to_string(), "1.0");
/// x.decrement();
/// assert_eq!(x.to_string(), "0.50");
///
/// let mut x = Float::one_prec(100);
/// assert_eq!(x.to_string(), "1.0000000000000000000000000000000");
/// x.decrement();
/// assert_eq!(x.to_string(), "0.99999999999999999999999999999921");
///
/// let mut x = Float::from(std::f64::consts::PI);
/// assert_eq!(x.to_string(), "3.1415926535897931");
/// x.decrement();
/// assert_eq!(x.to_string(), "3.1415926535897896");
///
/// let mut x = Float::power_of_2(100u64);
/// assert_eq!(x.to_string(), "1.3e30");
/// x.decrement();
/// assert_eq!(x.to_string(), "6.3e29");
///
/// let mut x = Float::power_of_2(-100i64);
/// assert_eq!(x.to_string(), "7.9e-31");
/// x.decrement();
/// assert_eq!(x.to_string(), "3.9e-31");
///
/// let mut x = Float::NEGATIVE_ONE;
/// assert_eq!(x.to_string(), "-1.0");
/// x.decrement();
/// assert_eq!(x.to_string(), "-2.0");
/// ```
pub fn decrement(&mut self) {
if self.is_sign_negative() {
self.neg_assign();
self.increment();
self.neg_assign();
} else if let Self(Finite {
exponent,
precision,
significand,
..
}) = self
{
let bits = significand_bits(significand);
let ulp = Limb::power_of_2(bits - *precision);
significand.sub_assign_at_limb(
usize::wrapping_from(significand.limb_count())
- 1
- bit_to_limb_count_floor(*precision - 1),
ulp,
);
if *significand == 0u32 {
// The value was a power of 2 with precision 1, so stepping down lands on the next
// power of 2, unless that is out of range.
if *exponent == Self::MIN_EXPONENT {
*self = Self::ZERO;
} else {
*significand = Natural::power_of_2(bits - 1);
*exponent -= 1;
}
} else if significand.significant_bits() < bits {
// The value was a power of 2 with precision greater than 1, so stepping down
// crosses into the next-lower binade, where the closest value is half an ulp away
// and has an all-ones significand with the same precision — unless the lower
// binade is out of range.
if *exponent == Self::MIN_EXPONENT {
*self = Self::ZERO;
return;
}
significand.set_bit(bits - 1);
*exponent -= 1;
}
} else {
panic!("Cannot decrement float that is non-finite or zero");
}
}
}