1 | //! Constants for the `f64` double-precision floating point type. |
2 | //! |
3 | //! *[See also the `f64` primitive type][f64].* |
4 | //! |
5 | //! Mathematically significant numbers are provided in the `consts` sub-module. |
6 | //! |
7 | //! For the constants defined directly in this module |
8 | //! (as distinct from those defined in the `consts` sub-module), |
9 | //! new code should instead use the associated constants |
10 | //! defined directly on the `f64` type. |
11 | |
12 | #![stable (feature = "rust1" , since = "1.0.0" )] |
13 | |
14 | use crate::convert::FloatToInt; |
15 | #[cfg (not(test))] |
16 | use crate::intrinsics; |
17 | use crate::mem; |
18 | use crate::num::FpCategory; |
19 | |
20 | /// The radix or base of the internal representation of `f64`. |
21 | /// Use [`f64::RADIX`] instead. |
22 | /// |
23 | /// # Examples |
24 | /// |
25 | /// ```rust |
26 | /// // deprecated way |
27 | /// # #[allow (deprecated, deprecated_in_future)] |
28 | /// let r = std::f64::RADIX; |
29 | /// |
30 | /// // intended way |
31 | /// let r = f64::RADIX; |
32 | /// ``` |
33 | #[stable (feature = "rust1" , since = "1.0.0" )] |
34 | #[deprecated (since = "TBD" , note = "replaced by the `RADIX` associated constant on `f64`" )] |
35 | #[rustc_diagnostic_item = "f64_legacy_const_radix" ] |
36 | pub const RADIX: u32 = f64::RADIX; |
37 | |
38 | /// Number of significant digits in base 2. |
39 | /// Use [`f64::MANTISSA_DIGITS`] instead. |
40 | /// |
41 | /// # Examples |
42 | /// |
43 | /// ```rust |
44 | /// // deprecated way |
45 | /// # #[allow (deprecated, deprecated_in_future)] |
46 | /// let d = std::f64::MANTISSA_DIGITS; |
47 | /// |
48 | /// // intended way |
49 | /// let d = f64::MANTISSA_DIGITS; |
50 | /// ``` |
51 | #[stable (feature = "rust1" , since = "1.0.0" )] |
52 | #[deprecated ( |
53 | since = "TBD" , |
54 | note = "replaced by the `MANTISSA_DIGITS` associated constant on `f64`" |
55 | )] |
56 | #[rustc_diagnostic_item = "f64_legacy_const_mantissa_dig" ] |
57 | pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS; |
58 | |
59 | /// Approximate number of significant digits in base 10. |
60 | /// Use [`f64::DIGITS`] instead. |
61 | /// |
62 | /// # Examples |
63 | /// |
64 | /// ```rust |
65 | /// // deprecated way |
66 | /// # #[allow (deprecated, deprecated_in_future)] |
67 | /// let d = std::f64::DIGITS; |
68 | /// |
69 | /// // intended way |
70 | /// let d = f64::DIGITS; |
71 | /// ``` |
72 | #[stable (feature = "rust1" , since = "1.0.0" )] |
73 | #[deprecated (since = "TBD" , note = "replaced by the `DIGITS` associated constant on `f64`" )] |
74 | #[rustc_diagnostic_item = "f64_legacy_const_digits" ] |
75 | pub const DIGITS: u32 = f64::DIGITS; |
76 | |
77 | /// [Machine epsilon] value for `f64`. |
78 | /// Use [`f64::EPSILON`] instead. |
79 | /// |
80 | /// This is the difference between `1.0` and the next larger representable number. |
81 | /// |
82 | /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon |
83 | /// |
84 | /// # Examples |
85 | /// |
86 | /// ```rust |
87 | /// // deprecated way |
88 | /// # #[allow (deprecated, deprecated_in_future)] |
89 | /// let e = std::f64::EPSILON; |
90 | /// |
91 | /// // intended way |
92 | /// let e = f64::EPSILON; |
93 | /// ``` |
94 | #[stable (feature = "rust1" , since = "1.0.0" )] |
95 | #[deprecated (since = "TBD" , note = "replaced by the `EPSILON` associated constant on `f64`" )] |
96 | #[rustc_diagnostic_item = "f64_legacy_const_epsilon" ] |
97 | pub const EPSILON: f64 = f64::EPSILON; |
98 | |
99 | /// Smallest finite `f64` value. |
100 | /// Use [`f64::MIN`] instead. |
101 | /// |
102 | /// # Examples |
103 | /// |
104 | /// ```rust |
105 | /// // deprecated way |
106 | /// # #[allow (deprecated, deprecated_in_future)] |
107 | /// let min = std::f64::MIN; |
108 | /// |
109 | /// // intended way |
110 | /// let min = f64::MIN; |
111 | /// ``` |
112 | #[stable (feature = "rust1" , since = "1.0.0" )] |
113 | #[deprecated (since = "TBD" , note = "replaced by the `MIN` associated constant on `f64`" )] |
114 | #[rustc_diagnostic_item = "f64_legacy_const_min" ] |
115 | pub const MIN: f64 = f64::MIN; |
116 | |
117 | /// Smallest positive normal `f64` value. |
118 | /// Use [`f64::MIN_POSITIVE`] instead. |
119 | /// |
120 | /// # Examples |
121 | /// |
122 | /// ```rust |
123 | /// // deprecated way |
124 | /// # #[allow (deprecated, deprecated_in_future)] |
125 | /// let min = std::f64::MIN_POSITIVE; |
126 | /// |
127 | /// // intended way |
128 | /// let min = f64::MIN_POSITIVE; |
129 | /// ``` |
130 | #[stable (feature = "rust1" , since = "1.0.0" )] |
131 | #[deprecated (since = "TBD" , note = "replaced by the `MIN_POSITIVE` associated constant on `f64`" )] |
132 | #[rustc_diagnostic_item = "f64_legacy_const_min_positive" ] |
133 | pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE; |
134 | |
135 | /// Largest finite `f64` value. |
136 | /// Use [`f64::MAX`] instead. |
137 | /// |
138 | /// # Examples |
139 | /// |
140 | /// ```rust |
141 | /// // deprecated way |
142 | /// # #[allow (deprecated, deprecated_in_future)] |
143 | /// let max = std::f64::MAX; |
144 | /// |
145 | /// // intended way |
146 | /// let max = f64::MAX; |
147 | /// ``` |
148 | #[stable (feature = "rust1" , since = "1.0.0" )] |
149 | #[deprecated (since = "TBD" , note = "replaced by the `MAX` associated constant on `f64`" )] |
150 | #[rustc_diagnostic_item = "f64_legacy_const_max" ] |
151 | pub const MAX: f64 = f64::MAX; |
152 | |
153 | /// One greater than the minimum possible normal power of 2 exponent. |
154 | /// Use [`f64::MIN_EXP`] instead. |
155 | /// |
156 | /// # Examples |
157 | /// |
158 | /// ```rust |
159 | /// // deprecated way |
160 | /// # #[allow (deprecated, deprecated_in_future)] |
161 | /// let min = std::f64::MIN_EXP; |
162 | /// |
163 | /// // intended way |
164 | /// let min = f64::MIN_EXP; |
165 | /// ``` |
166 | #[stable (feature = "rust1" , since = "1.0.0" )] |
167 | #[deprecated (since = "TBD" , note = "replaced by the `MIN_EXP` associated constant on `f64`" )] |
168 | #[rustc_diagnostic_item = "f64_legacy_const_min_exp" ] |
169 | pub const MIN_EXP: i32 = f64::MIN_EXP; |
170 | |
171 | /// Maximum possible power of 2 exponent. |
172 | /// Use [`f64::MAX_EXP`] instead. |
173 | /// |
174 | /// # Examples |
175 | /// |
176 | /// ```rust |
177 | /// // deprecated way |
178 | /// # #[allow (deprecated, deprecated_in_future)] |
179 | /// let max = std::f64::MAX_EXP; |
180 | /// |
181 | /// // intended way |
182 | /// let max = f64::MAX_EXP; |
183 | /// ``` |
184 | #[stable (feature = "rust1" , since = "1.0.0" )] |
185 | #[deprecated (since = "TBD" , note = "replaced by the `MAX_EXP` associated constant on `f64`" )] |
186 | #[rustc_diagnostic_item = "f64_legacy_const_max_exp" ] |
187 | pub const MAX_EXP: i32 = f64::MAX_EXP; |
188 | |
189 | /// Minimum possible normal power of 10 exponent. |
190 | /// Use [`f64::MIN_10_EXP`] instead. |
191 | /// |
192 | /// # Examples |
193 | /// |
194 | /// ```rust |
195 | /// // deprecated way |
196 | /// # #[allow (deprecated, deprecated_in_future)] |
197 | /// let min = std::f64::MIN_10_EXP; |
198 | /// |
199 | /// // intended way |
200 | /// let min = f64::MIN_10_EXP; |
201 | /// ``` |
202 | #[stable (feature = "rust1" , since = "1.0.0" )] |
203 | #[deprecated (since = "TBD" , note = "replaced by the `MIN_10_EXP` associated constant on `f64`" )] |
204 | #[rustc_diagnostic_item = "f64_legacy_const_min_10_exp" ] |
205 | pub const MIN_10_EXP: i32 = f64::MIN_10_EXP; |
206 | |
207 | /// Maximum possible power of 10 exponent. |
208 | /// Use [`f64::MAX_10_EXP`] instead. |
209 | /// |
210 | /// # Examples |
211 | /// |
212 | /// ```rust |
213 | /// // deprecated way |
214 | /// # #[allow (deprecated, deprecated_in_future)] |
215 | /// let max = std::f64::MAX_10_EXP; |
216 | /// |
217 | /// // intended way |
218 | /// let max = f64::MAX_10_EXP; |
219 | /// ``` |
220 | #[stable (feature = "rust1" , since = "1.0.0" )] |
221 | #[deprecated (since = "TBD" , note = "replaced by the `MAX_10_EXP` associated constant on `f64`" )] |
222 | #[rustc_diagnostic_item = "f64_legacy_const_max_10_exp" ] |
223 | pub const MAX_10_EXP: i32 = f64::MAX_10_EXP; |
224 | |
225 | /// Not a Number (NaN). |
226 | /// Use [`f64::NAN`] instead. |
227 | /// |
228 | /// # Examples |
229 | /// |
230 | /// ```rust |
231 | /// // deprecated way |
232 | /// # #[allow (deprecated, deprecated_in_future)] |
233 | /// let nan = std::f64::NAN; |
234 | /// |
235 | /// // intended way |
236 | /// let nan = f64::NAN; |
237 | /// ``` |
238 | #[stable (feature = "rust1" , since = "1.0.0" )] |
239 | #[deprecated (since = "TBD" , note = "replaced by the `NAN` associated constant on `f64`" )] |
240 | #[rustc_diagnostic_item = "f64_legacy_const_nan" ] |
241 | pub const NAN: f64 = f64::NAN; |
242 | |
243 | /// Infinity (∞). |
244 | /// Use [`f64::INFINITY`] instead. |
245 | /// |
246 | /// # Examples |
247 | /// |
248 | /// ```rust |
249 | /// // deprecated way |
250 | /// # #[allow (deprecated, deprecated_in_future)] |
251 | /// let inf = std::f64::INFINITY; |
252 | /// |
253 | /// // intended way |
254 | /// let inf = f64::INFINITY; |
255 | /// ``` |
256 | #[stable (feature = "rust1" , since = "1.0.0" )] |
257 | #[deprecated (since = "TBD" , note = "replaced by the `INFINITY` associated constant on `f64`" )] |
258 | #[rustc_diagnostic_item = "f64_legacy_const_infinity" ] |
259 | pub const INFINITY: f64 = f64::INFINITY; |
260 | |
261 | /// Negative infinity (−∞). |
262 | /// Use [`f64::NEG_INFINITY`] instead. |
263 | /// |
264 | /// # Examples |
265 | /// |
266 | /// ```rust |
267 | /// // deprecated way |
268 | /// # #[allow (deprecated, deprecated_in_future)] |
269 | /// let ninf = std::f64::NEG_INFINITY; |
270 | /// |
271 | /// // intended way |
272 | /// let ninf = f64::NEG_INFINITY; |
273 | /// ``` |
274 | #[stable (feature = "rust1" , since = "1.0.0" )] |
275 | #[deprecated (since = "TBD" , note = "replaced by the `NEG_INFINITY` associated constant on `f64`" )] |
276 | #[rustc_diagnostic_item = "f64_legacy_const_neg_infinity" ] |
277 | pub const NEG_INFINITY: f64 = f64::NEG_INFINITY; |
278 | |
279 | /// Basic mathematical constants. |
280 | #[stable (feature = "rust1" , since = "1.0.0" )] |
281 | pub mod consts { |
282 | // FIXME: replace with mathematical constants from cmath. |
283 | |
284 | /// Archimedes' constant (π) |
285 | #[stable (feature = "rust1" , since = "1.0.0" )] |
286 | pub const PI: f64 = 3.14159265358979323846264338327950288_f64; |
287 | |
288 | /// The full circle constant (τ) |
289 | /// |
290 | /// Equal to 2π. |
291 | #[stable (feature = "tau_constant" , since = "1.47.0" )] |
292 | pub const TAU: f64 = 6.28318530717958647692528676655900577_f64; |
293 | |
294 | /// The golden ratio (φ) |
295 | #[unstable (feature = "more_float_constants" , issue = "103883" )] |
296 | pub const PHI: f64 = 1.618033988749894848204586834365638118_f64; |
297 | |
298 | /// The Euler-Mascheroni constant (γ) |
299 | #[unstable (feature = "more_float_constants" , issue = "103883" )] |
300 | pub const EGAMMA: f64 = 0.577215664901532860606512090082402431_f64; |
301 | |
302 | /// π/2 |
303 | #[stable (feature = "rust1" , since = "1.0.0" )] |
304 | pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; |
305 | |
306 | /// π/3 |
307 | #[stable (feature = "rust1" , since = "1.0.0" )] |
308 | pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; |
309 | |
310 | /// π/4 |
311 | #[stable (feature = "rust1" , since = "1.0.0" )] |
312 | pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; |
313 | |
314 | /// π/6 |
315 | #[stable (feature = "rust1" , since = "1.0.0" )] |
316 | pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; |
317 | |
318 | /// π/8 |
319 | #[stable (feature = "rust1" , since = "1.0.0" )] |
320 | pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; |
321 | |
322 | /// 1/π |
323 | #[stable (feature = "rust1" , since = "1.0.0" )] |
324 | pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; |
325 | |
326 | /// 1/sqrt(π) |
327 | #[unstable (feature = "more_float_constants" , issue = "103883" )] |
328 | pub const FRAC_1_SQRT_PI: f64 = 0.564189583547756286948079451560772586_f64; |
329 | |
330 | /// 2/π |
331 | #[stable (feature = "rust1" , since = "1.0.0" )] |
332 | pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; |
333 | |
334 | /// 2/sqrt(π) |
335 | #[stable (feature = "rust1" , since = "1.0.0" )] |
336 | pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64; |
337 | |
338 | /// sqrt(2) |
339 | #[stable (feature = "rust1" , since = "1.0.0" )] |
340 | pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64; |
341 | |
342 | /// 1/sqrt(2) |
343 | #[stable (feature = "rust1" , since = "1.0.0" )] |
344 | pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64; |
345 | |
346 | /// sqrt(3) |
347 | #[unstable (feature = "more_float_constants" , issue = "103883" )] |
348 | pub const SQRT_3: f64 = 1.732050807568877293527446341505872367_f64; |
349 | |
350 | /// 1/sqrt(3) |
351 | #[unstable (feature = "more_float_constants" , issue = "103883" )] |
352 | pub const FRAC_1_SQRT_3: f64 = 0.577350269189625764509148780501957456_f64; |
353 | |
354 | /// Euler's number (e) |
355 | #[stable (feature = "rust1" , since = "1.0.0" )] |
356 | pub const E: f64 = 2.71828182845904523536028747135266250_f64; |
357 | |
358 | /// log<sub>2</sub>(10) |
359 | #[stable (feature = "extra_log_consts" , since = "1.43.0" )] |
360 | pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64; |
361 | |
362 | /// log<sub>2</sub>(e) |
363 | #[stable (feature = "rust1" , since = "1.0.0" )] |
364 | pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; |
365 | |
366 | /// log<sub>10</sub>(2) |
367 | #[stable (feature = "extra_log_consts" , since = "1.43.0" )] |
368 | pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64; |
369 | |
370 | /// log<sub>10</sub>(e) |
371 | #[stable (feature = "rust1" , since = "1.0.0" )] |
372 | pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; |
373 | |
374 | /// ln(2) |
375 | #[stable (feature = "rust1" , since = "1.0.0" )] |
376 | pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; |
377 | |
378 | /// ln(10) |
379 | #[stable (feature = "rust1" , since = "1.0.0" )] |
380 | pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; |
381 | } |
382 | |
383 | #[cfg (not(test))] |
384 | impl f64 { |
385 | /// The radix or base of the internal representation of `f64`. |
386 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
387 | pub const RADIX: u32 = 2; |
388 | |
389 | /// Number of significant digits in base 2. |
390 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
391 | pub const MANTISSA_DIGITS: u32 = 53; |
392 | /// Approximate number of significant digits in base 10. |
393 | /// |
394 | /// This is the maximum <i>x</i> such that any decimal number with <i>x</i> |
395 | /// significant digits can be converted to `f64` and back without loss. |
396 | /// |
397 | /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>). |
398 | /// |
399 | /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS |
400 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
401 | pub const DIGITS: u32 = 15; |
402 | |
403 | /// [Machine epsilon] value for `f64`. |
404 | /// |
405 | /// This is the difference between `1.0` and the next larger representable number. |
406 | /// |
407 | /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>. |
408 | /// |
409 | /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon |
410 | /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS |
411 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
412 | pub const EPSILON: f64 = 2.2204460492503131e-16_f64; |
413 | |
414 | /// Smallest finite `f64` value. |
415 | /// |
416 | /// Equal to −[`MAX`]. |
417 | /// |
418 | /// [`MAX`]: f64::MAX |
419 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
420 | pub const MIN: f64 = -1.7976931348623157e+308_f64; |
421 | /// Smallest positive normal `f64` value. |
422 | /// |
423 | /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>. |
424 | /// |
425 | /// [`MIN_EXP`]: f64::MIN_EXP |
426 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
427 | pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64; |
428 | /// Largest finite `f64` value. |
429 | /// |
430 | /// Equal to |
431 | /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>. |
432 | /// |
433 | /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS |
434 | /// [`MAX_EXP`]: f64::MAX_EXP |
435 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
436 | pub const MAX: f64 = 1.7976931348623157e+308_f64; |
437 | |
438 | /// One greater than the minimum possible normal power of 2 exponent. |
439 | /// |
440 | /// If <i>x</i> = `MIN_EXP`, then normal numbers |
441 | /// ≥ 0.5 × 2<sup><i>x</i></sup>. |
442 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
443 | pub const MIN_EXP: i32 = -1021; |
444 | /// Maximum possible power of 2 exponent. |
445 | /// |
446 | /// If <i>x</i> = `MAX_EXP`, then normal numbers |
447 | /// < 1 × 2<sup><i>x</i></sup>. |
448 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
449 | pub const MAX_EXP: i32 = 1024; |
450 | |
451 | /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal. |
452 | /// |
453 | /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]). |
454 | /// |
455 | /// [`MIN_POSITIVE`]: f64::MIN_POSITIVE |
456 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
457 | pub const MIN_10_EXP: i32 = -307; |
458 | /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal. |
459 | /// |
460 | /// Equal to floor(log<sub>10</sub> [`MAX`]). |
461 | /// |
462 | /// [`MAX`]: f64::MAX |
463 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
464 | pub const MAX_10_EXP: i32 = 308; |
465 | |
466 | /// Not a Number (NaN). |
467 | /// |
468 | /// Note that IEEE 754 doesn't define just a single NaN value; |
469 | /// a plethora of bit patterns are considered to be NaN. |
470 | /// Furthermore, the standard makes a difference |
471 | /// between a "signaling" and a "quiet" NaN, |
472 | /// and allows inspecting its "payload" (the unspecified bits in the bit pattern). |
473 | /// This constant isn't guaranteed to equal to any specific NaN bitpattern, |
474 | /// and the stability of its representation over Rust versions |
475 | /// and target platforms isn't guaranteed. |
476 | #[rustc_diagnostic_item = "f64_nan" ] |
477 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
478 | #[allow (clippy::eq_op)] |
479 | pub const NAN: f64 = 0.0_f64 / 0.0_f64; |
480 | /// Infinity (∞). |
481 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
482 | pub const INFINITY: f64 = 1.0_f64 / 0.0_f64; |
483 | /// Negative infinity (−∞). |
484 | #[stable (feature = "assoc_int_consts" , since = "1.43.0" )] |
485 | pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64; |
486 | |
487 | /// Returns `true` if this value is NaN. |
488 | /// |
489 | /// ``` |
490 | /// let nan = f64::NAN; |
491 | /// let f = 7.0_f64; |
492 | /// |
493 | /// assert!(nan.is_nan()); |
494 | /// assert!(!f.is_nan()); |
495 | /// ``` |
496 | #[must_use ] |
497 | #[stable (feature = "rust1" , since = "1.0.0" )] |
498 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
499 | #[inline ] |
500 | #[allow (clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :) |
501 | pub const fn is_nan(self) -> bool { |
502 | self != self |
503 | } |
504 | |
505 | // FIXME(#50145): `abs` is publicly unavailable in core due to |
506 | // concerns about portability, so this implementation is for |
507 | // private use internally. |
508 | #[inline ] |
509 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
510 | pub(crate) const fn abs_private(self) -> f64 { |
511 | // SAFETY: This transmutation is fine. Probably. For the reasons std is using it. |
512 | unsafe { |
513 | mem::transmute::<u64, f64>(mem::transmute::<f64, u64>(self) & 0x7fff_ffff_ffff_ffff) |
514 | } |
515 | } |
516 | |
517 | /// Returns `true` if this value is positive infinity or negative infinity, and |
518 | /// `false` otherwise. |
519 | /// |
520 | /// ``` |
521 | /// let f = 7.0f64; |
522 | /// let inf = f64::INFINITY; |
523 | /// let neg_inf = f64::NEG_INFINITY; |
524 | /// let nan = f64::NAN; |
525 | /// |
526 | /// assert!(!f.is_infinite()); |
527 | /// assert!(!nan.is_infinite()); |
528 | /// |
529 | /// assert!(inf.is_infinite()); |
530 | /// assert!(neg_inf.is_infinite()); |
531 | /// ``` |
532 | #[must_use ] |
533 | #[stable (feature = "rust1" , since = "1.0.0" )] |
534 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
535 | #[inline ] |
536 | pub const fn is_infinite(self) -> bool { |
537 | // Getting clever with transmutation can result in incorrect answers on some FPUs |
538 | // FIXME: alter the Rust <-> Rust calling convention to prevent this problem. |
539 | // See https://github.com/rust-lang/rust/issues/72327 |
540 | (self == f64::INFINITY) | (self == f64::NEG_INFINITY) |
541 | } |
542 | |
543 | /// Returns `true` if this number is neither infinite nor NaN. |
544 | /// |
545 | /// ``` |
546 | /// let f = 7.0f64; |
547 | /// let inf: f64 = f64::INFINITY; |
548 | /// let neg_inf: f64 = f64::NEG_INFINITY; |
549 | /// let nan: f64 = f64::NAN; |
550 | /// |
551 | /// assert!(f.is_finite()); |
552 | /// |
553 | /// assert!(!nan.is_finite()); |
554 | /// assert!(!inf.is_finite()); |
555 | /// assert!(!neg_inf.is_finite()); |
556 | /// ``` |
557 | #[must_use ] |
558 | #[stable (feature = "rust1" , since = "1.0.0" )] |
559 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
560 | #[inline ] |
561 | pub const fn is_finite(self) -> bool { |
562 | // There's no need to handle NaN separately: if self is NaN, |
563 | // the comparison is not true, exactly as desired. |
564 | self.abs_private() < Self::INFINITY |
565 | } |
566 | |
567 | /// Returns `true` if the number is [subnormal]. |
568 | /// |
569 | /// ``` |
570 | /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64 |
571 | /// let max = f64::MAX; |
572 | /// let lower_than_min = 1.0e-308_f64; |
573 | /// let zero = 0.0_f64; |
574 | /// |
575 | /// assert!(!min.is_subnormal()); |
576 | /// assert!(!max.is_subnormal()); |
577 | /// |
578 | /// assert!(!zero.is_subnormal()); |
579 | /// assert!(!f64::NAN.is_subnormal()); |
580 | /// assert!(!f64::INFINITY.is_subnormal()); |
581 | /// // Values between `0` and `min` are Subnormal. |
582 | /// assert!(lower_than_min.is_subnormal()); |
583 | /// ``` |
584 | /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number |
585 | #[must_use ] |
586 | #[stable (feature = "is_subnormal" , since = "1.53.0" )] |
587 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
588 | #[inline ] |
589 | pub const fn is_subnormal(self) -> bool { |
590 | matches!(self.classify(), FpCategory::Subnormal) |
591 | } |
592 | |
593 | /// Returns `true` if the number is neither zero, infinite, |
594 | /// [subnormal], or NaN. |
595 | /// |
596 | /// ``` |
597 | /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64 |
598 | /// let max = f64::MAX; |
599 | /// let lower_than_min = 1.0e-308_f64; |
600 | /// let zero = 0.0f64; |
601 | /// |
602 | /// assert!(min.is_normal()); |
603 | /// assert!(max.is_normal()); |
604 | /// |
605 | /// assert!(!zero.is_normal()); |
606 | /// assert!(!f64::NAN.is_normal()); |
607 | /// assert!(!f64::INFINITY.is_normal()); |
608 | /// // Values between `0` and `min` are Subnormal. |
609 | /// assert!(!lower_than_min.is_normal()); |
610 | /// ``` |
611 | /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number |
612 | #[must_use ] |
613 | #[stable (feature = "rust1" , since = "1.0.0" )] |
614 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
615 | #[inline ] |
616 | pub const fn is_normal(self) -> bool { |
617 | matches!(self.classify(), FpCategory::Normal) |
618 | } |
619 | |
620 | /// Returns the floating point category of the number. If only one property |
621 | /// is going to be tested, it is generally faster to use the specific |
622 | /// predicate instead. |
623 | /// |
624 | /// ``` |
625 | /// use std::num::FpCategory; |
626 | /// |
627 | /// let num = 12.4_f64; |
628 | /// let inf = f64::INFINITY; |
629 | /// |
630 | /// assert_eq!(num.classify(), FpCategory::Normal); |
631 | /// assert_eq!(inf.classify(), FpCategory::Infinite); |
632 | /// ``` |
633 | #[stable (feature = "rust1" , since = "1.0.0" )] |
634 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
635 | pub const fn classify(self) -> FpCategory { |
636 | // A previous implementation tried to only use bitmask-based checks, |
637 | // using f64::to_bits to transmute the float to its bit repr and match on that. |
638 | // Unfortunately, floating point numbers can be much worse than that. |
639 | // This also needs to not result in recursive evaluations of f64::to_bits. |
640 | // |
641 | // On some processors, in some cases, LLVM will "helpfully" lower floating point ops, |
642 | // in spite of a request for them using f32 and f64, to things like x87 operations. |
643 | // These have an f64's mantissa, but can have a larger than normal exponent. |
644 | // FIXME(jubilee): Using x87 operations is never necessary in order to function |
645 | // on x86 processors for Rust-to-Rust calls, so this issue should not happen. |
646 | // Code generation should be adjusted to use non-C calling conventions, avoiding this. |
647 | // |
648 | // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask. |
649 | // And it may not be NaN, as it can simply be an "overextended" finite value. |
650 | if self.is_nan() { |
651 | FpCategory::Nan |
652 | } else { |
653 | // However, std can't simply compare to zero to check for zero, either, |
654 | // as correctness requires avoiding equality tests that may be Subnormal == -0.0 |
655 | // because it may be wrong under "denormals are zero" and "flush to zero" modes. |
656 | // Most of std's targets don't use those, but they are used for thumbv7neon. |
657 | // So, this does use bitpattern matching for the rest. |
658 | |
659 | // SAFETY: f64 to u64 is fine. Usually. |
660 | // If control flow has gotten this far, the value is definitely in one of the categories |
661 | // that f64::partial_classify can correctly analyze. |
662 | unsafe { f64::partial_classify(self) } |
663 | } |
664 | } |
665 | |
666 | // This doesn't actually return a right answer for NaN on purpose, |
667 | // seeing as how it cannot correctly discern between a floating point NaN, |
668 | // and some normal floating point numbers truncated from an x87 FPU. |
669 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
670 | const unsafe fn partial_classify(self) -> FpCategory { |
671 | const EXP_MASK: u64 = 0x7ff0000000000000; |
672 | const MAN_MASK: u64 = 0x000fffffffffffff; |
673 | |
674 | // SAFETY: The caller is not asking questions for which this will tell lies. |
675 | let b = unsafe { mem::transmute::<f64, u64>(self) }; |
676 | match (b & MAN_MASK, b & EXP_MASK) { |
677 | (0, EXP_MASK) => FpCategory::Infinite, |
678 | (0, 0) => FpCategory::Zero, |
679 | (_, 0) => FpCategory::Subnormal, |
680 | _ => FpCategory::Normal, |
681 | } |
682 | } |
683 | |
684 | // This operates on bits, and only bits, so it can ignore concerns about weird FPUs. |
685 | // FIXME(jubilee): In a just world, this would be the entire impl for classify, |
686 | // plus a transmute. We do not live in a just world, but we can make it more so. |
687 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
688 | const fn classify_bits(b: u64) -> FpCategory { |
689 | const EXP_MASK: u64 = 0x7ff0000000000000; |
690 | const MAN_MASK: u64 = 0x000fffffffffffff; |
691 | |
692 | match (b & MAN_MASK, b & EXP_MASK) { |
693 | (0, EXP_MASK) => FpCategory::Infinite, |
694 | (_, EXP_MASK) => FpCategory::Nan, |
695 | (0, 0) => FpCategory::Zero, |
696 | (_, 0) => FpCategory::Subnormal, |
697 | _ => FpCategory::Normal, |
698 | } |
699 | } |
700 | |
701 | /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with |
702 | /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any |
703 | /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that |
704 | /// the bit pattern of NaNs are conserved over arithmetic operations, the result of |
705 | /// `is_sign_positive` on a NaN might produce an unexpected result in some cases. |
706 | /// See [explanation of NaN as a special value](f32) for more info. |
707 | /// |
708 | /// ``` |
709 | /// let f = 7.0_f64; |
710 | /// let g = -7.0_f64; |
711 | /// |
712 | /// assert!(f.is_sign_positive()); |
713 | /// assert!(!g.is_sign_positive()); |
714 | /// ``` |
715 | #[must_use ] |
716 | #[stable (feature = "rust1" , since = "1.0.0" )] |
717 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
718 | #[inline ] |
719 | pub const fn is_sign_positive(self) -> bool { |
720 | !self.is_sign_negative() |
721 | } |
722 | |
723 | #[must_use ] |
724 | #[stable (feature = "rust1" , since = "1.0.0" )] |
725 | #[deprecated (since = "1.0.0" , note = "renamed to is_sign_positive" )] |
726 | #[inline ] |
727 | #[doc (hidden)] |
728 | pub fn is_positive(self) -> bool { |
729 | self.is_sign_positive() |
730 | } |
731 | |
732 | /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with |
733 | /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any |
734 | /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that |
735 | /// the bit pattern of NaNs are conserved over arithmetic operations, the result of |
736 | /// `is_sign_negative` on a NaN might produce an unexpected result in some cases. |
737 | /// See [explanation of NaN as a special value](f32) for more info. |
738 | /// |
739 | /// ``` |
740 | /// let f = 7.0_f64; |
741 | /// let g = -7.0_f64; |
742 | /// |
743 | /// assert!(!f.is_sign_negative()); |
744 | /// assert!(g.is_sign_negative()); |
745 | /// ``` |
746 | #[must_use ] |
747 | #[stable (feature = "rust1" , since = "1.0.0" )] |
748 | #[rustc_const_unstable (feature = "const_float_classify" , issue = "72505" )] |
749 | #[inline ] |
750 | pub const fn is_sign_negative(self) -> bool { |
751 | // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus |
752 | // applies to zeros and NaNs as well. |
753 | // SAFETY: This is just transmuting to get the sign bit, it's fine. |
754 | unsafe { mem::transmute::<f64, u64>(self) & 0x8000_0000_0000_0000 != 0 } |
755 | } |
756 | |
757 | #[must_use ] |
758 | #[stable (feature = "rust1" , since = "1.0.0" )] |
759 | #[deprecated (since = "1.0.0" , note = "renamed to is_sign_negative" )] |
760 | #[inline ] |
761 | #[doc (hidden)] |
762 | pub fn is_negative(self) -> bool { |
763 | self.is_sign_negative() |
764 | } |
765 | |
766 | /// Returns the least number greater than `self`. |
767 | /// |
768 | /// Let `TINY` be the smallest representable positive `f64`. Then, |
769 | /// - if `self.is_nan()`, this returns `self`; |
770 | /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`]; |
771 | /// - if `self` is `-TINY`, this returns -0.0; |
772 | /// - if `self` is -0.0 or +0.0, this returns `TINY`; |
773 | /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`]; |
774 | /// - otherwise the unique least value greater than `self` is returned. |
775 | /// |
776 | /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x` |
777 | /// is finite `x == x.next_up().next_down()` also holds. |
778 | /// |
779 | /// ```rust |
780 | /// #![feature(float_next_up_down)] |
781 | /// // f64::EPSILON is the difference between 1.0 and the next number up. |
782 | /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON); |
783 | /// // But not for most numbers. |
784 | /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON); |
785 | /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0); |
786 | /// ``` |
787 | /// |
788 | /// [`NEG_INFINITY`]: Self::NEG_INFINITY |
789 | /// [`INFINITY`]: Self::INFINITY |
790 | /// [`MIN`]: Self::MIN |
791 | /// [`MAX`]: Self::MAX |
792 | #[unstable (feature = "float_next_up_down" , issue = "91399" )] |
793 | #[rustc_const_unstable (feature = "float_next_up_down" , issue = "91399" )] |
794 | pub const fn next_up(self) -> Self { |
795 | // We must use strictly integer arithmetic to prevent denormals from |
796 | // flushing to zero after an arithmetic operation on some platforms. |
797 | const TINY_BITS: u64 = 0x1; // Smallest positive f64. |
798 | const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff; |
799 | |
800 | let bits = self.to_bits(); |
801 | if self.is_nan() || bits == Self::INFINITY.to_bits() { |
802 | return self; |
803 | } |
804 | |
805 | let abs = bits & CLEAR_SIGN_MASK; |
806 | let next_bits = if abs == 0 { |
807 | TINY_BITS |
808 | } else if bits == abs { |
809 | bits + 1 |
810 | } else { |
811 | bits - 1 |
812 | }; |
813 | Self::from_bits(next_bits) |
814 | } |
815 | |
816 | /// Returns the greatest number less than `self`. |
817 | /// |
818 | /// Let `TINY` be the smallest representable positive `f64`. Then, |
819 | /// - if `self.is_nan()`, this returns `self`; |
820 | /// - if `self` is [`INFINITY`], this returns [`MAX`]; |
821 | /// - if `self` is `TINY`, this returns 0.0; |
822 | /// - if `self` is -0.0 or +0.0, this returns `-TINY`; |
823 | /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`]; |
824 | /// - otherwise the unique greatest value less than `self` is returned. |
825 | /// |
826 | /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x` |
827 | /// is finite `x == x.next_down().next_up()` also holds. |
828 | /// |
829 | /// ```rust |
830 | /// #![feature(float_next_up_down)] |
831 | /// let x = 1.0f64; |
832 | /// // Clamp value into range [0, 1). |
833 | /// let clamped = x.clamp(0.0, 1.0f64.next_down()); |
834 | /// assert!(clamped < 1.0); |
835 | /// assert_eq!(clamped.next_up(), 1.0); |
836 | /// ``` |
837 | /// |
838 | /// [`NEG_INFINITY`]: Self::NEG_INFINITY |
839 | /// [`INFINITY`]: Self::INFINITY |
840 | /// [`MIN`]: Self::MIN |
841 | /// [`MAX`]: Self::MAX |
842 | #[unstable (feature = "float_next_up_down" , issue = "91399" )] |
843 | #[rustc_const_unstable (feature = "float_next_up_down" , issue = "91399" )] |
844 | pub const fn next_down(self) -> Self { |
845 | // We must use strictly integer arithmetic to prevent denormals from |
846 | // flushing to zero after an arithmetic operation on some platforms. |
847 | const NEG_TINY_BITS: u64 = 0x8000_0000_0000_0001; // Smallest (in magnitude) negative f64. |
848 | const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff; |
849 | |
850 | let bits = self.to_bits(); |
851 | if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() { |
852 | return self; |
853 | } |
854 | |
855 | let abs = bits & CLEAR_SIGN_MASK; |
856 | let next_bits = if abs == 0 { |
857 | NEG_TINY_BITS |
858 | } else if bits == abs { |
859 | bits - 1 |
860 | } else { |
861 | bits + 1 |
862 | }; |
863 | Self::from_bits(next_bits) |
864 | } |
865 | |
866 | /// Takes the reciprocal (inverse) of a number, `1/x`. |
867 | /// |
868 | /// ``` |
869 | /// let x = 2.0_f64; |
870 | /// let abs_difference = (x.recip() - (1.0 / x)).abs(); |
871 | /// |
872 | /// assert!(abs_difference < 1e-10); |
873 | /// ``` |
874 | #[must_use = "this returns the result of the operation, without modifying the original" ] |
875 | #[stable (feature = "rust1" , since = "1.0.0" )] |
876 | #[inline ] |
877 | pub fn recip(self) -> f64 { |
878 | 1.0 / self |
879 | } |
880 | |
881 | /// Converts radians to degrees. |
882 | /// |
883 | /// ``` |
884 | /// let angle = std::f64::consts::PI; |
885 | /// |
886 | /// let abs_difference = (angle.to_degrees() - 180.0).abs(); |
887 | /// |
888 | /// assert!(abs_difference < 1e-10); |
889 | /// ``` |
890 | #[must_use = "this returns the result of the operation, \ |
891 | without modifying the original" ] |
892 | #[stable (feature = "rust1" , since = "1.0.0" )] |
893 | #[inline ] |
894 | pub fn to_degrees(self) -> f64 { |
895 | // The division here is correctly rounded with respect to the true |
896 | // value of 180/π. (This differs from f32, where a constant must be |
897 | // used to ensure a correctly rounded result.) |
898 | self * (180.0f64 / consts::PI) |
899 | } |
900 | |
901 | /// Converts degrees to radians. |
902 | /// |
903 | /// ``` |
904 | /// let angle = 180.0_f64; |
905 | /// |
906 | /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs(); |
907 | /// |
908 | /// assert!(abs_difference < 1e-10); |
909 | /// ``` |
910 | #[must_use = "this returns the result of the operation, \ |
911 | without modifying the original" ] |
912 | #[stable (feature = "rust1" , since = "1.0.0" )] |
913 | #[inline ] |
914 | pub fn to_radians(self) -> f64 { |
915 | let value: f64 = consts::PI; |
916 | self * (value / 180.0) |
917 | } |
918 | |
919 | /// Returns the maximum of the two numbers, ignoring NaN. |
920 | /// |
921 | /// If one of the arguments is NaN, then the other argument is returned. |
922 | /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs; |
923 | /// this function handles all NaNs the same way and avoids maxNum's problems with associativity. |
924 | /// This also matches the behavior of libm’s fmax. |
925 | /// |
926 | /// ``` |
927 | /// let x = 1.0_f64; |
928 | /// let y = 2.0_f64; |
929 | /// |
930 | /// assert_eq!(x.max(y), y); |
931 | /// ``` |
932 | #[must_use = "this returns the result of the comparison, without modifying either input" ] |
933 | #[stable (feature = "rust1" , since = "1.0.0" )] |
934 | #[inline ] |
935 | pub fn max(self, other: f64) -> f64 { |
936 | intrinsics::maxnumf64(self, other) |
937 | } |
938 | |
939 | /// Returns the minimum of the two numbers, ignoring NaN. |
940 | /// |
941 | /// If one of the arguments is NaN, then the other argument is returned. |
942 | /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs; |
943 | /// this function handles all NaNs the same way and avoids minNum's problems with associativity. |
944 | /// This also matches the behavior of libm’s fmin. |
945 | /// |
946 | /// ``` |
947 | /// let x = 1.0_f64; |
948 | /// let y = 2.0_f64; |
949 | /// |
950 | /// assert_eq!(x.min(y), x); |
951 | /// ``` |
952 | #[must_use = "this returns the result of the comparison, without modifying either input" ] |
953 | #[stable (feature = "rust1" , since = "1.0.0" )] |
954 | #[inline ] |
955 | pub fn min(self, other: f64) -> f64 { |
956 | intrinsics::minnumf64(self, other) |
957 | } |
958 | |
959 | /// Returns the maximum of the two numbers, propagating NaN. |
960 | /// |
961 | /// This returns NaN when *either* argument is NaN, as opposed to |
962 | /// [`f64::max`] which only returns NaN when *both* arguments are NaN. |
963 | /// |
964 | /// ``` |
965 | /// #![feature(float_minimum_maximum)] |
966 | /// let x = 1.0_f64; |
967 | /// let y = 2.0_f64; |
968 | /// |
969 | /// assert_eq!(x.maximum(y), y); |
970 | /// assert!(x.maximum(f64::NAN).is_nan()); |
971 | /// ``` |
972 | /// |
973 | /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater |
974 | /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0. |
975 | /// Note that this follows the semantics specified in IEEE 754-2019. |
976 | /// |
977 | /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN |
978 | /// operand is conserved; see [explanation of NaN as a special value](f32) for more info. |
979 | #[must_use = "this returns the result of the comparison, without modifying either input" ] |
980 | #[unstable (feature = "float_minimum_maximum" , issue = "91079" )] |
981 | #[inline ] |
982 | pub fn maximum(self, other: f64) -> f64 { |
983 | if self > other { |
984 | self |
985 | } else if other > self { |
986 | other |
987 | } else if self == other { |
988 | if self.is_sign_positive() && other.is_sign_negative() { self } else { other } |
989 | } else { |
990 | self + other |
991 | } |
992 | } |
993 | |
994 | /// Returns the minimum of the two numbers, propagating NaN. |
995 | /// |
996 | /// This returns NaN when *either* argument is NaN, as opposed to |
997 | /// [`f64::min`] which only returns NaN when *both* arguments are NaN. |
998 | /// |
999 | /// ``` |
1000 | /// #![feature(float_minimum_maximum)] |
1001 | /// let x = 1.0_f64; |
1002 | /// let y = 2.0_f64; |
1003 | /// |
1004 | /// assert_eq!(x.minimum(y), x); |
1005 | /// assert!(x.minimum(f64::NAN).is_nan()); |
1006 | /// ``` |
1007 | /// |
1008 | /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser |
1009 | /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0. |
1010 | /// Note that this follows the semantics specified in IEEE 754-2019. |
1011 | /// |
1012 | /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN |
1013 | /// operand is conserved; see [explanation of NaN as a special value](f32) for more info. |
1014 | #[must_use = "this returns the result of the comparison, without modifying either input" ] |
1015 | #[unstable (feature = "float_minimum_maximum" , issue = "91079" )] |
1016 | #[inline ] |
1017 | pub fn minimum(self, other: f64) -> f64 { |
1018 | if self < other { |
1019 | self |
1020 | } else if other < self { |
1021 | other |
1022 | } else if self == other { |
1023 | if self.is_sign_negative() && other.is_sign_positive() { self } else { other } |
1024 | } else { |
1025 | // At least one input is NaN. Use `+` to perform NaN propagation and quieting. |
1026 | self + other |
1027 | } |
1028 | } |
1029 | |
1030 | /// Calculates the middle point of `self` and `rhs`. |
1031 | /// |
1032 | /// This returns NaN when *either* argument is NaN or if a combination of |
1033 | /// +inf and -inf is provided as arguments. |
1034 | /// |
1035 | /// # Examples |
1036 | /// |
1037 | /// ``` |
1038 | /// #![feature(num_midpoint)] |
1039 | /// assert_eq!(1f64.midpoint(4.0), 2.5); |
1040 | /// assert_eq!((-5.5f64).midpoint(8.0), 1.25); |
1041 | /// ``` |
1042 | #[unstable (feature = "num_midpoint" , issue = "110840" )] |
1043 | pub fn midpoint(self, other: f64) -> f64 { |
1044 | const LO: f64 = f64::MIN_POSITIVE * 2.; |
1045 | const HI: f64 = f64::MAX / 2.; |
1046 | |
1047 | let (a, b) = (self, other); |
1048 | let abs_a = a.abs_private(); |
1049 | let abs_b = b.abs_private(); |
1050 | |
1051 | if abs_a <= HI && abs_b <= HI { |
1052 | // Overflow is impossible |
1053 | (a + b) / 2. |
1054 | } else if abs_a < LO { |
1055 | // Not safe to halve a |
1056 | a + (b / 2.) |
1057 | } else if abs_b < LO { |
1058 | // Not safe to halve b |
1059 | (a / 2.) + b |
1060 | } else { |
1061 | // Not safe to halve a and b |
1062 | (a / 2.) + (b / 2.) |
1063 | } |
1064 | } |
1065 | |
1066 | /// Rounds toward zero and converts to any primitive integer type, |
1067 | /// assuming that the value is finite and fits in that type. |
1068 | /// |
1069 | /// ``` |
1070 | /// let value = 4.6_f64; |
1071 | /// let rounded = unsafe { value.to_int_unchecked::<u16>() }; |
1072 | /// assert_eq!(rounded, 4); |
1073 | /// |
1074 | /// let value = -128.9_f64; |
1075 | /// let rounded = unsafe { value.to_int_unchecked::<i8>() }; |
1076 | /// assert_eq!(rounded, i8::MIN); |
1077 | /// ``` |
1078 | /// |
1079 | /// # Safety |
1080 | /// |
1081 | /// The value must: |
1082 | /// |
1083 | /// * Not be `NaN` |
1084 | /// * Not be infinite |
1085 | /// * Be representable in the return type `Int`, after truncating off its fractional part |
1086 | #[must_use = "this returns the result of the operation, \ |
1087 | without modifying the original" ] |
1088 | #[stable (feature = "float_approx_unchecked_to" , since = "1.44.0" )] |
1089 | #[inline ] |
1090 | pub unsafe fn to_int_unchecked<Int>(self) -> Int |
1091 | where |
1092 | Self: FloatToInt<Int>, |
1093 | { |
1094 | // SAFETY: the caller must uphold the safety contract for |
1095 | // `FloatToInt::to_int_unchecked`. |
1096 | unsafe { FloatToInt::<Int>::to_int_unchecked(self) } |
1097 | } |
1098 | |
1099 | /// Raw transmutation to `u64`. |
1100 | /// |
1101 | /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms. |
1102 | /// |
1103 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1104 | /// portability of this operation (there are almost no issues). |
1105 | /// |
1106 | /// Note that this function is distinct from `as` casting, which attempts to |
1107 | /// preserve the *numeric* value, and not the bitwise value. |
1108 | /// |
1109 | /// # Examples |
1110 | /// |
1111 | /// ``` |
1112 | /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting! |
1113 | /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000); |
1114 | /// |
1115 | /// ``` |
1116 | #[must_use = "this returns the result of the operation, \ |
1117 | without modifying the original" ] |
1118 | #[stable (feature = "float_bits_conv" , since = "1.20.0" )] |
1119 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1120 | #[inline ] |
1121 | pub const fn to_bits(self) -> u64 { |
1122 | // SAFETY: `u64` is a plain old datatype so we can always transmute to it. |
1123 | // ...sorta. |
1124 | // |
1125 | // See the SAFETY comment in f64::from_bits for more. |
1126 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1127 | const fn ct_f64_to_u64(ct: f64) -> u64 { |
1128 | match ct.classify() { |
1129 | FpCategory::Nan => { |
1130 | panic!("const-eval error: cannot use f64::to_bits on a NaN" ) |
1131 | } |
1132 | FpCategory::Subnormal => { |
1133 | panic!("const-eval error: cannot use f64::to_bits on a subnormal number" ) |
1134 | } |
1135 | FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => { |
1136 | // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy. |
1137 | unsafe { mem::transmute::<f64, u64>(ct) } |
1138 | } |
1139 | } |
1140 | } |
1141 | |
1142 | #[inline (always)] // See https://github.com/rust-lang/compiler-builtins/issues/491 |
1143 | fn rt_f64_to_u64(rt: f64) -> u64 { |
1144 | // SAFETY: `u64` is a plain old datatype so we can always... uh... |
1145 | // ...look, just pretend you forgot what you just read. |
1146 | // Stability concerns. |
1147 | unsafe { mem::transmute::<f64, u64>(rt) } |
1148 | } |
1149 | intrinsics::const_eval_select((self,), ct_f64_to_u64, rt_f64_to_u64) |
1150 | } |
1151 | |
1152 | /// Raw transmutation from `u64`. |
1153 | /// |
1154 | /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms. |
1155 | /// It turns out this is incredibly portable, for two reasons: |
1156 | /// |
1157 | /// * Floats and Ints have the same endianness on all supported platforms. |
1158 | /// * IEEE 754 very precisely specifies the bit layout of floats. |
1159 | /// |
1160 | /// However there is one caveat: prior to the 2008 version of IEEE 754, how |
1161 | /// to interpret the NaN signaling bit wasn't actually specified. Most platforms |
1162 | /// (notably x86 and ARM) picked the interpretation that was ultimately |
1163 | /// standardized in 2008, but some didn't (notably MIPS). As a result, all |
1164 | /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa. |
1165 | /// |
1166 | /// Rather than trying to preserve signaling-ness cross-platform, this |
1167 | /// implementation favors preserving the exact bits. This means that |
1168 | /// any payloads encoded in NaNs will be preserved even if the result of |
1169 | /// this method is sent over the network from an x86 machine to a MIPS one. |
1170 | /// |
1171 | /// If the results of this method are only manipulated by the same |
1172 | /// architecture that produced them, then there is no portability concern. |
1173 | /// |
1174 | /// If the input isn't NaN, then there is no portability concern. |
1175 | /// |
1176 | /// If you don't care about signaling-ness (very likely), then there is no |
1177 | /// portability concern. |
1178 | /// |
1179 | /// Note that this function is distinct from `as` casting, which attempts to |
1180 | /// preserve the *numeric* value, and not the bitwise value. |
1181 | /// |
1182 | /// # Examples |
1183 | /// |
1184 | /// ``` |
1185 | /// let v = f64::from_bits(0x4029000000000000); |
1186 | /// assert_eq!(v, 12.5); |
1187 | /// ``` |
1188 | #[stable (feature = "float_bits_conv" , since = "1.20.0" )] |
1189 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1190 | #[must_use ] |
1191 | #[inline ] |
1192 | pub const fn from_bits(v: u64) -> Self { |
1193 | // It turns out the safety issues with sNaN were overblown! Hooray! |
1194 | // SAFETY: `u64` is a plain old datatype so we can always transmute from it |
1195 | // ...sorta. |
1196 | // |
1197 | // It turns out that at runtime, it is possible for a floating point number |
1198 | // to be subject to floating point modes that alter nonzero subnormal numbers |
1199 | // to zero on reads and writes, aka "denormals are zero" and "flush to zero". |
1200 | // This is not a problem usually, but at least one tier2 platform for Rust |
1201 | // actually exhibits an FTZ behavior by default: thumbv7neon |
1202 | // aka "the Neon FPU in AArch32 state" |
1203 | // |
1204 | // Even with this, not all instructions exhibit the FTZ behaviors on thumbv7neon, |
1205 | // so this should load the same bits if LLVM emits the "correct" instructions, |
1206 | // but LLVM sometimes makes interesting choices about float optimization, |
1207 | // and other FPUs may do similar. Thus, it is wise to indulge luxuriously in caution. |
1208 | // |
1209 | // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled, |
1210 | // i.e. not soft-float, the way Rust does parameter passing can actually alter |
1211 | // a number that is "not infinity" to have the same exponent as infinity, |
1212 | // in a slightly unpredictable manner. |
1213 | // |
1214 | // And, of course evaluating to a NaN value is fairly nondeterministic. |
1215 | // More precisely: when NaN should be returned is knowable, but which NaN? |
1216 | // So far that's defined by a combination of LLVM and the CPU, not Rust. |
1217 | // This function, however, allows observing the bitstring of a NaN, |
1218 | // thus introspection on CTFE. |
1219 | // |
1220 | // In order to preserve, at least for the moment, const-to-runtime equivalence, |
1221 | // reject any of these possible situations from happening. |
1222 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1223 | const fn ct_u64_to_f64(ct: u64) -> f64 { |
1224 | match f64::classify_bits(ct) { |
1225 | FpCategory::Subnormal => { |
1226 | panic!("const-eval error: cannot use f64::from_bits on a subnormal number" ) |
1227 | } |
1228 | FpCategory::Nan => { |
1229 | panic!("const-eval error: cannot use f64::from_bits on NaN" ) |
1230 | } |
1231 | FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => { |
1232 | // SAFETY: It's not a frumious number |
1233 | unsafe { mem::transmute::<u64, f64>(ct) } |
1234 | } |
1235 | } |
1236 | } |
1237 | |
1238 | #[inline (always)] // See https://github.com/rust-lang/compiler-builtins/issues/491 |
1239 | fn rt_u64_to_f64(rt: u64) -> f64 { |
1240 | // SAFETY: `u64` is a plain old datatype so we can always... uh... |
1241 | // ...look, just pretend you forgot what you just read. |
1242 | // Stability concerns. |
1243 | unsafe { mem::transmute::<u64, f64>(rt) } |
1244 | } |
1245 | intrinsics::const_eval_select((v,), ct_u64_to_f64, rt_u64_to_f64) |
1246 | } |
1247 | |
1248 | /// Return the memory representation of this floating point number as a byte array in |
1249 | /// big-endian (network) byte order. |
1250 | /// |
1251 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1252 | /// portability of this operation (there are almost no issues). |
1253 | /// |
1254 | /// # Examples |
1255 | /// |
1256 | /// ``` |
1257 | /// let bytes = 12.5f64.to_be_bytes(); |
1258 | /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); |
1259 | /// ``` |
1260 | #[must_use = "this returns the result of the operation, \ |
1261 | without modifying the original" ] |
1262 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1263 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1264 | #[inline ] |
1265 | pub const fn to_be_bytes(self) -> [u8; 8] { |
1266 | self.to_bits().to_be_bytes() |
1267 | } |
1268 | |
1269 | /// Return the memory representation of this floating point number as a byte array in |
1270 | /// little-endian byte order. |
1271 | /// |
1272 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1273 | /// portability of this operation (there are almost no issues). |
1274 | /// |
1275 | /// # Examples |
1276 | /// |
1277 | /// ``` |
1278 | /// let bytes = 12.5f64.to_le_bytes(); |
1279 | /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]); |
1280 | /// ``` |
1281 | #[must_use = "this returns the result of the operation, \ |
1282 | without modifying the original" ] |
1283 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1284 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1285 | #[inline ] |
1286 | pub const fn to_le_bytes(self) -> [u8; 8] { |
1287 | self.to_bits().to_le_bytes() |
1288 | } |
1289 | |
1290 | /// Return the memory representation of this floating point number as a byte array in |
1291 | /// native byte order. |
1292 | /// |
1293 | /// As the target platform's native endianness is used, portable code |
1294 | /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead. |
1295 | /// |
1296 | /// [`to_be_bytes`]: f64::to_be_bytes |
1297 | /// [`to_le_bytes`]: f64::to_le_bytes |
1298 | /// |
1299 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1300 | /// portability of this operation (there are almost no issues). |
1301 | /// |
1302 | /// # Examples |
1303 | /// |
1304 | /// ``` |
1305 | /// let bytes = 12.5f64.to_ne_bytes(); |
1306 | /// assert_eq!( |
1307 | /// bytes, |
1308 | /// if cfg!(target_endian = "big" ) { |
1309 | /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] |
1310 | /// } else { |
1311 | /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40] |
1312 | /// } |
1313 | /// ); |
1314 | /// ``` |
1315 | #[must_use = "this returns the result of the operation, \ |
1316 | without modifying the original" ] |
1317 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1318 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1319 | #[inline ] |
1320 | pub const fn to_ne_bytes(self) -> [u8; 8] { |
1321 | self.to_bits().to_ne_bytes() |
1322 | } |
1323 | |
1324 | /// Create a floating point value from its representation as a byte array in big endian. |
1325 | /// |
1326 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1327 | /// portability of this operation (there are almost no issues). |
1328 | /// |
1329 | /// # Examples |
1330 | /// |
1331 | /// ``` |
1332 | /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); |
1333 | /// assert_eq!(value, 12.5); |
1334 | /// ``` |
1335 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1336 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1337 | #[must_use ] |
1338 | #[inline ] |
1339 | pub const fn from_be_bytes(bytes: [u8; 8]) -> Self { |
1340 | Self::from_bits(u64::from_be_bytes(bytes)) |
1341 | } |
1342 | |
1343 | /// Create a floating point value from its representation as a byte array in little endian. |
1344 | /// |
1345 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1346 | /// portability of this operation (there are almost no issues). |
1347 | /// |
1348 | /// # Examples |
1349 | /// |
1350 | /// ``` |
1351 | /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]); |
1352 | /// assert_eq!(value, 12.5); |
1353 | /// ``` |
1354 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1355 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1356 | #[must_use ] |
1357 | #[inline ] |
1358 | pub const fn from_le_bytes(bytes: [u8; 8]) -> Self { |
1359 | Self::from_bits(u64::from_le_bytes(bytes)) |
1360 | } |
1361 | |
1362 | /// Create a floating point value from its representation as a byte array in native endian. |
1363 | /// |
1364 | /// As the target platform's native endianness is used, portable code |
1365 | /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as |
1366 | /// appropriate instead. |
1367 | /// |
1368 | /// [`from_be_bytes`]: f64::from_be_bytes |
1369 | /// [`from_le_bytes`]: f64::from_le_bytes |
1370 | /// |
1371 | /// See [`from_bits`](Self::from_bits) for some discussion of the |
1372 | /// portability of this operation (there are almost no issues). |
1373 | /// |
1374 | /// # Examples |
1375 | /// |
1376 | /// ``` |
1377 | /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big" ) { |
1378 | /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] |
1379 | /// } else { |
1380 | /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40] |
1381 | /// }); |
1382 | /// assert_eq!(value, 12.5); |
1383 | /// ``` |
1384 | #[stable (feature = "float_to_from_bytes" , since = "1.40.0" )] |
1385 | #[rustc_const_unstable (feature = "const_float_bits_conv" , issue = "72447" )] |
1386 | #[must_use ] |
1387 | #[inline ] |
1388 | pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self { |
1389 | Self::from_bits(u64::from_ne_bytes(bytes)) |
1390 | } |
1391 | |
1392 | /// Return the ordering between `self` and `other`. |
1393 | /// |
1394 | /// Unlike the standard partial comparison between floating point numbers, |
1395 | /// this comparison always produces an ordering in accordance to |
1396 | /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision) |
1397 | /// floating point standard. The values are ordered in the following sequence: |
1398 | /// |
1399 | /// - negative quiet NaN |
1400 | /// - negative signaling NaN |
1401 | /// - negative infinity |
1402 | /// - negative numbers |
1403 | /// - negative subnormal numbers |
1404 | /// - negative zero |
1405 | /// - positive zero |
1406 | /// - positive subnormal numbers |
1407 | /// - positive numbers |
1408 | /// - positive infinity |
1409 | /// - positive signaling NaN |
1410 | /// - positive quiet NaN. |
1411 | /// |
1412 | /// The ordering established by this function does not always agree with the |
1413 | /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example, |
1414 | /// they consider negative and positive zero equal, while `total_cmp` |
1415 | /// doesn't. |
1416 | /// |
1417 | /// The interpretation of the signaling NaN bit follows the definition in |
1418 | /// the IEEE 754 standard, which may not match the interpretation by some of |
1419 | /// the older, non-conformant (e.g. MIPS) hardware implementations. |
1420 | /// |
1421 | /// # Example |
1422 | /// |
1423 | /// ``` |
1424 | /// struct GoodBoy { |
1425 | /// name: String, |
1426 | /// weight: f64, |
1427 | /// } |
1428 | /// |
1429 | /// let mut bois = vec![ |
1430 | /// GoodBoy { name: "Pucci" .to_owned(), weight: 0.1 }, |
1431 | /// GoodBoy { name: "Woofer" .to_owned(), weight: 99.0 }, |
1432 | /// GoodBoy { name: "Yapper" .to_owned(), weight: 10.0 }, |
1433 | /// GoodBoy { name: "Chonk" .to_owned(), weight: f64::INFINITY }, |
1434 | /// GoodBoy { name: "Abs. Unit" .to_owned(), weight: f64::NAN }, |
1435 | /// GoodBoy { name: "Floaty" .to_owned(), weight: -5.0 }, |
1436 | /// ]; |
1437 | /// |
1438 | /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight)); |
1439 | /// |
1440 | /// // `f64::NAN` could be positive or negative, which will affect the sort order. |
1441 | /// if f64::NAN.is_sign_negative() { |
1442 | /// assert!(bois.into_iter().map(|b| b.weight) |
1443 | /// .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter()) |
1444 | /// .all(|(a, b)| a.to_bits() == b.to_bits())) |
1445 | /// } else { |
1446 | /// assert!(bois.into_iter().map(|b| b.weight) |
1447 | /// .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter()) |
1448 | /// .all(|(a, b)| a.to_bits() == b.to_bits())) |
1449 | /// } |
1450 | /// ``` |
1451 | #[stable (feature = "total_cmp" , since = "1.62.0" )] |
1452 | #[must_use ] |
1453 | #[inline ] |
1454 | pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { |
1455 | let mut left = self.to_bits() as i64; |
1456 | let mut right = other.to_bits() as i64; |
1457 | |
1458 | // In case of negatives, flip all the bits except the sign |
1459 | // to achieve a similar layout as two's complement integers |
1460 | // |
1461 | // Why does this work? IEEE 754 floats consist of three fields: |
1462 | // Sign bit, exponent and mantissa. The set of exponent and mantissa |
1463 | // fields as a whole have the property that their bitwise order is |
1464 | // equal to the numeric magnitude where the magnitude is defined. |
1465 | // The magnitude is not normally defined on NaN values, but |
1466 | // IEEE 754 totalOrder defines the NaN values also to follow the |
1467 | // bitwise order. This leads to order explained in the doc comment. |
1468 | // However, the representation of magnitude is the same for negative |
1469 | // and positive numbers – only the sign bit is different. |
1470 | // To easily compare the floats as signed integers, we need to |
1471 | // flip the exponent and mantissa bits in case of negative numbers. |
1472 | // We effectively convert the numbers to "two's complement" form. |
1473 | // |
1474 | // To do the flipping, we construct a mask and XOR against it. |
1475 | // We branchlessly calculate an "all-ones except for the sign bit" |
1476 | // mask from negative-signed values: right shifting sign-extends |
1477 | // the integer, so we "fill" the mask with sign bits, and then |
1478 | // convert to unsigned to push one more zero bit. |
1479 | // On positive values, the mask is all zeros, so it's a no-op. |
1480 | left ^= (((left >> 63) as u64) >> 1) as i64; |
1481 | right ^= (((right >> 63) as u64) >> 1) as i64; |
1482 | |
1483 | left.cmp(&right) |
1484 | } |
1485 | |
1486 | /// Restrict a value to a certain interval unless it is NaN. |
1487 | /// |
1488 | /// Returns `max` if `self` is greater than `max`, and `min` if `self` is |
1489 | /// less than `min`. Otherwise this returns `self`. |
1490 | /// |
1491 | /// Note that this function returns NaN if the initial value was NaN as |
1492 | /// well. |
1493 | /// |
1494 | /// # Panics |
1495 | /// |
1496 | /// Panics if `min > max`, `min` is NaN, or `max` is NaN. |
1497 | /// |
1498 | /// # Examples |
1499 | /// |
1500 | /// ``` |
1501 | /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0); |
1502 | /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0); |
1503 | /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0); |
1504 | /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan()); |
1505 | /// ``` |
1506 | #[must_use = "method returns a new number and does not mutate the original value" ] |
1507 | #[stable (feature = "clamp" , since = "1.50.0" )] |
1508 | #[inline ] |
1509 | pub fn clamp(mut self, min: f64, max: f64) -> f64 { |
1510 | assert!(min <= max, "min > max, or either was NaN. min = {min:?}, max = {max:?}" ); |
1511 | if self < min { |
1512 | self = min; |
1513 | } |
1514 | if self > max { |
1515 | self = max; |
1516 | } |
1517 | self |
1518 | } |
1519 | } |
1520 | |