malachite_float/conversion/mantissa_and_exponent.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::Float;
10use crate::InnerFloat::Finite;
11use core::cmp::{
12 Ordering::{self, *},
13 min,
14};
15use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2;
16use malachite_base::num::basic::floats::PrimitiveFloat;
17use malachite_base::num::basic::integers::PrimitiveInt;
18use malachite_base::num::conversion::traits::{
19 ExactFrom, IntegerMantissaAndExponent, RawMantissaAndExponent, SciMantissaAndExponent,
20};
21use malachite_base::num::logic::traits::SignificantBits;
22use malachite_base::rounding_modes::RoundingMode::{self, *};
23use malachite_nz::natural::Natural;
24use malachite_nz::platform::Limb;
25
26impl Float {
27 /// Returns a [`Float`]'s scientific mantissa and exponent, rounding according to the specified
28 /// rounding mode. An [`Ordering`] is also returned, indicating whether the mantissa and
29 /// exponent represent a value that is less than, equal to, or greater than the original value.
30 ///
31 /// When $x$ is positive, we can write $x = 2^{e_s}m_s$, where $e_s$ is an integer and $m_s$ is
32 /// a rational number with $1 \leq m_s < 2$. We represent the rational mantissa as a float. The
33 /// conversion might not be exact, so we round to the nearest float using the provided rounding
34 /// mode. If the rounding mode is `Exact` but the conversion is not exact, `None` is returned.
35 /// $$
36 /// f(x, r) \approx \left (\frac{x}{2^{\lfloor \log_2 x \rfloor}},
37 /// \lfloor \log_2 x \rfloor\right ).
38 /// $$
39 ///
40 /// This function does not overflow or underflow. The returned exponent is always in the range
41 /// $[-2^{30}, 2^{30}-1]$. Notice that although a [`Float`]'s maximum scientific exponent is
42 /// $2^{30}-2$, this function may return an exponent one larger than this limit due to rounding.
43 ///
44 /// # Worst-case complexity
45 /// $T(n) = O(n)$
46 ///
47 /// $M(n) = O(1)$
48 ///
49 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
50 ///
51 /// # Examples
52 /// ```
53 /// use malachite_base::num::arithmetic::traits::Pow;
54 /// use malachite_base::num::conversion::traits::ExactFrom;
55 /// use malachite_base::num::float::NiceFloat;
56 /// use malachite_base::rounding_modes::RoundingMode::{self, *};
57 /// use malachite_float::Float;
58 /// use malachite_nz::natural::Natural;
59 /// use std::cmp::Ordering::{self, *};
60 ///
61 /// let test = |x: Float, rm: RoundingMode, out: Option<(f32, i32, Ordering)>| {
62 /// assert_eq!(
63 /// x.sci_mantissa_and_exponent_round(rm)
64 /// .map(|(m, e, o)| (NiceFloat(m), e, o)),
65 /// out.map(|(m, e, o)| (NiceFloat(m), e, o))
66 /// );
67 /// };
68 /// test(Float::from(3u32), Floor, Some((1.5, 1, Equal)));
69 /// test(Float::from(3u32), Down, Some((1.5, 1, Equal)));
70 /// test(Float::from(3u32), Ceiling, Some((1.5, 1, Equal)));
71 /// test(Float::from(3u32), Up, Some((1.5, 1, Equal)));
72 /// test(Float::from(3u32), Nearest, Some((1.5, 1, Equal)));
73 /// test(Float::from(3u32), Exact, Some((1.5, 1, Equal)));
74 ///
75 /// let x = Float::from(std::f64::consts::PI);
76 /// test(x.clone(), Floor, Some((1.5707963, 1, Less)));
77 /// test(x.clone(), Down, Some((1.5707963, 1, Less)));
78 /// test(x.clone(), Ceiling, Some((1.5707964, 1, Greater)));
79 /// test(x.clone(), Up, Some((1.5707964, 1, Greater)));
80 /// test(x.clone(), Nearest, Some((1.5707964, 1, Greater)));
81 /// test(x.clone(), Exact, None);
82 ///
83 /// test(
84 /// Float::from(1000000000u32),
85 /// Nearest,
86 /// Some((1.8626451, 29, Equal)),
87 /// );
88 /// test(
89 /// Float::exact_from(Natural::from(10u32).pow(52)),
90 /// Nearest,
91 /// Some((1.670478, 172, Greater)),
92 /// );
93 ///
94 /// test(Float::exact_from(Natural::from(10u32).pow(52)), Exact, None);
95 /// ```
96 pub fn sci_mantissa_and_exponent_round<T: PrimitiveFloat>(
97 &self,
98 rm: RoundingMode,
99 ) -> Option<(T, i32, Ordering)> {
100 match self {
101 Float(Finite {
102 exponent,
103 significand,
104 ..
105 }) => significand
106 .sci_mantissa_and_exponent_round::<T>(rm)
107 .map(|(m, _, o)| {
108 (
109 m,
110 if o == Greater && m == T::ONE {
111 *exponent
112 } else {
113 exponent - 1
114 },
115 o,
116 )
117 }),
118 _ => None,
119 }
120 }
121}
122
123impl RawMantissaAndExponent<Natural, i32> for Float {
124 /// Returns the raw mantissa and exponent of a [`Float`], taking the [`Float`] by value.
125 ///
126 /// The raw exponent and raw mantissa are the actual bit patterns used to represent the
127 /// components of `self`. When `self` is finite and nonzero, the raw mantissa is an integer
128 /// whose number of significant bits is a multiple of the limb width, and which is equal to the
129 /// absolute value of `self` multiplied by some integer power of 2. The raw exponent is one more
130 /// than the floor of the base-2 logarithm of the absolute value of `self`.
131 ///
132 /// The inverse operation is [`Self::from_raw_mantissa_and_exponent`].
133 ///
134 /// The raw exponent is in the range $[-(2^{30}-1), 2^{30}-1]$.
135 ///
136 /// # Worst-case complexity
137 /// Constant time and additional memory.
138 ///
139 /// # Panics
140 /// Panics if the [`Float`] is not finite or not zero.
141 ///
142 /// # Examples
143 /// ```
144 /// use malachite_base::num::arithmetic::traits::Pow;
145 /// use malachite_base::num::basic::integers::PrimitiveInt;
146 /// use malachite_base::num::basic::traits::One;
147 /// use malachite_base::num::conversion::traits::{ExactFrom, RawMantissaAndExponent};
148 /// use malachite_float::Float;
149 /// use malachite_nz::natural::Natural;
150 /// use malachite_nz::platform::Limb;
151 /// use malachite_q::Rational;
152 ///
153 /// if Limb::WIDTH == u64::WIDTH {
154 /// let (m, e) = Float::ONE.raw_mantissa_and_exponent();
155 /// assert_eq!(m.to_string(), "9223372036854775808");
156 /// assert_eq!(e, 1);
157 ///
158 /// let (m, e) = Float::from(std::f64::consts::PI).raw_mantissa_and_exponent();
159 /// assert_eq!(m.to_string(), "14488038916154245120");
160 /// assert_eq!(e, 2);
161 ///
162 /// let (m, e) =
163 /// Float::exact_from(Natural::from(3u32).pow(50u64)).raw_mantissa_and_exponent();
164 /// assert_eq!(m.to_string(), "202070319366191015160784900114134073344");
165 /// assert_eq!(e, 80);
166 ///
167 /// let (m, e) = Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
168 /// .0
169 /// .raw_mantissa_and_exponent();
170 /// assert_eq!(m.to_string(), "286514342137199872022965541161805021184");
171 /// assert_eq!(e, -79);
172 /// }
173 /// ```
174 fn raw_mantissa_and_exponent(self) -> (Natural, i32) {
175 if let Float(Finite {
176 exponent,
177 significand,
178 ..
179 }) = self
180 {
181 (significand, exponent)
182 } else {
183 panic!()
184 }
185 }
186
187 /// Returns the raw exponent of a [`Float`], taking the [`Float`] by value.
188 ///
189 /// The raw exponent is one more than the floor of the base-2 logarithm of the absolute value of
190 /// `self`.
191 ///
192 /// The raw exponent is in the range $[-(2^{30}-1), 2^{30}-1]$.
193 ///
194 /// # Worst-case complexity
195 /// Constant time and additional memory.
196 ///
197 /// # Panics
198 /// Panics if the [`Float`] is not finite or not zero.
199 ///
200 /// # Examples
201 /// ```
202 /// use malachite_base::num::arithmetic::traits::Pow;
203 /// use malachite_base::num::basic::traits::One;
204 /// use malachite_base::num::conversion::traits::{ExactFrom, RawMantissaAndExponent};
205 /// use malachite_float::Float;
206 /// use malachite_nz::natural::Natural;
207 /// use malachite_q::Rational;
208 ///
209 /// assert_eq!(Float::ONE.raw_exponent(), 1);
210 /// assert_eq!(Float::from(std::f64::consts::PI).raw_exponent(), 2);
211 /// assert_eq!(
212 /// Float::exact_from(Natural::from(3u32).pow(50u64)).raw_exponent(),
213 /// 80
214 /// );
215 /// assert_eq!(
216 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
217 /// .0
218 /// .raw_exponent(),
219 /// -79
220 /// );
221 /// ```
222 fn raw_exponent(self) -> i32 {
223 if let Float(Finite { exponent, .. }) = self {
224 exponent
225 } else {
226 panic!()
227 }
228 }
229
230 /// Constructs a [`Float`] from its raw mantissa and exponent. The resulting [`Float`] is
231 /// positive and has the smallest precision possible.
232 ///
233 /// The number of significant bits of the raw mantissa must be divisible by the limb width. The
234 /// raw exponent must be in the range $[-(2^{30}-1), 2^{30}-1]$.
235 ///
236 /// # Worst-case complexity
237 /// Constant time and additional memory.
238 ///
239 /// # Panics
240 /// Panics if `raw_mantissa` is zero, if its number of significant bits is not divisible by the
241 /// limb width, or if `raw_exponent` is out of range.
242 ///
243 /// # Examples
244 /// ```
245 /// use malachite_base::num::arithmetic::traits::Pow;
246 /// use malachite_base::num::basic::integers::PrimitiveInt;
247 /// use malachite_base::num::conversion::traits::RawMantissaAndExponent;
248 /// use malachite_float::Float;
249 /// use malachite_nz::natural::Natural;
250 /// use malachite_nz::platform::Limb;
251 /// use malachite_q::Rational;
252 /// use std::str::FromStr;
253 ///
254 /// if Limb::WIDTH == u64::WIDTH {
255 /// assert_eq!(
256 /// Float::from_raw_mantissa_and_exponent(Natural::from(9223372036854775808u64), 1),
257 /// 1
258 /// );
259 /// assert_eq!(
260 /// Float::from_raw_mantissa_and_exponent(Natural::from(14488038916154245120u64), 2),
261 /// std::f64::consts::PI
262 /// );
263 /// assert_eq!(
264 /// Float::from_raw_mantissa_and_exponent(
265 /// Natural::from_str("202070319366191015160784900114134073344").unwrap(),
266 /// 80
267 /// ),
268 /// Natural::from(3u32).pow(50u64)
269 /// );
270 /// assert_eq!(
271 /// Float::from_raw_mantissa_and_exponent(
272 /// Natural::from_str("286514342137199872022965541161805021184").unwrap(),
273 /// -79
274 /// ),
275 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
276 /// );
277 /// }
278 /// ```
279 fn from_raw_mantissa_and_exponent(raw_mantissa: Natural, raw_exponent: i32) -> Float {
280 assert!(raw_exponent <= Float::MAX_EXPONENT);
281 assert!(raw_exponent >= Float::MIN_EXPONENT);
282 let bits = raw_mantissa.significant_bits();
283 assert_ne!(bits, 0);
284 assert!(bits.divisible_by_power_of_2(Limb::LOG_WIDTH));
285 let precision = bits - min(raw_mantissa.trailing_zeros().unwrap(), Limb::WIDTH - 1);
286 Float(Finite {
287 sign: true,
288 exponent: raw_exponent,
289 significand: raw_mantissa,
290 precision,
291 })
292 }
293}
294
295impl RawMantissaAndExponent<Natural, i32, Float> for &Float {
296 /// Returns the raw mantissa and exponent of a [`Float`], taking the [`Float`] by reference.
297 ///
298 /// The raw exponent and raw mantissa are the actual bit patterns used to represent the
299 /// components of `self`. When `self` is finite and nonzero, the raw mantissa is an integer
300 /// whose number of significant bits is a multiple of the limb width, and which is equal to the
301 /// absolute value of `self` multiplied by some integer power of 2. The raw exponent is one more
302 /// than the floor of the base-2 logarithm of the absolute value of `self`.
303 ///
304 /// The raw exponent is in the range $[-(2^{30}-1), 2^{30}-1]$.
305 ///
306 /// The inverse operation is [`Float::from_raw_mantissa_and_exponent`].
307 ///
308 /// # Worst-case complexity
309 /// $T(n) = O(n)$
310 ///
311 /// $M(n) = O(n)$
312 ///
313 /// where $T$ is time, $M$ is additional memory, and $n$ is `f.significant_bits()`.
314 ///
315 /// # Panics
316 /// Panics if the [`Float`] is not finite or not zero.
317 ///
318 /// # Examples
319 /// ```
320 /// use malachite_base::num::arithmetic::traits::Pow;
321 /// use malachite_base::num::basic::integers::PrimitiveInt;
322 /// use malachite_base::num::basic::traits::One;
323 /// use malachite_base::num::conversion::traits::{ExactFrom, RawMantissaAndExponent};
324 /// use malachite_float::Float;
325 /// use malachite_nz::natural::Natural;
326 /// use malachite_nz::platform::Limb;
327 /// use malachite_q::Rational;
328 ///
329 /// if Limb::WIDTH == u64::WIDTH {
330 /// let (m, e) = (&Float::ONE).raw_mantissa_and_exponent();
331 /// assert_eq!(m.to_string(), "9223372036854775808");
332 /// assert_eq!(e, 1);
333 ///
334 /// let (m, e) = (&Float::from(std::f64::consts::PI)).raw_mantissa_and_exponent();
335 /// assert_eq!(m.to_string(), "14488038916154245120");
336 /// assert_eq!(e, 2);
337 ///
338 /// let (m, e) =
339 /// (&Float::exact_from(Natural::from(3u32).pow(50u64))).raw_mantissa_and_exponent();
340 /// assert_eq!(m.to_string(), "202070319366191015160784900114134073344");
341 /// assert_eq!(e, 80);
342 ///
343 /// let (m, e) = (&Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0)
344 /// .raw_mantissa_and_exponent();
345 /// assert_eq!(m.to_string(), "286514342137199872022965541161805021184");
346 /// assert_eq!(e, -79);
347 /// }
348 /// ```
349 fn raw_mantissa_and_exponent(self) -> (Natural, i32) {
350 if let Float(Finite {
351 exponent,
352 significand,
353 ..
354 }) = self
355 {
356 (significand.clone(), *exponent)
357 } else {
358 panic!()
359 }
360 }
361
362 /// Returns the raw exponent of a [`Float`], taking the [`Float`] by reference.
363 ///
364 /// The raw exponent is one more than the floor of the base-2 logarithm of the absolute value of
365 /// `self`.
366 ///
367 /// The raw exponent is in the range $[-(2^{30}-1), 2^{30}-1]$.
368 ///
369 /// # Worst-case complexity
370 /// Constant time and additional memory.
371 ///
372 /// # Panics
373 /// Panics if the [`Float`] is not finite or not zero.
374 ///
375 /// # Examples
376 /// ```
377 /// use malachite_base::num::arithmetic::traits::Pow;
378 /// use malachite_base::num::basic::traits::One;
379 /// use malachite_base::num::conversion::traits::{ExactFrom, RawMantissaAndExponent};
380 /// use malachite_float::Float;
381 /// use malachite_nz::natural::Natural;
382 /// use malachite_q::Rational;
383 ///
384 /// assert_eq!((&Float::ONE).raw_exponent(), 1);
385 /// assert_eq!((&Float::from(std::f64::consts::PI)).raw_exponent(), 2);
386 /// assert_eq!(
387 /// (&Float::exact_from(Natural::from(3u32).pow(50u64))).raw_exponent(),
388 /// 80
389 /// );
390 /// assert_eq!(
391 /// (&Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0).raw_exponent(),
392 /// -79
393 /// );
394 /// ```
395 fn raw_exponent(self) -> i32 {
396 if let Float(Finite { exponent, .. }) = self {
397 *exponent
398 } else {
399 panic!()
400 }
401 }
402
403 /// Constructs a [`Float`] from its raw mantissa and exponent. The resulting [`Float`] is
404 /// positive and has the smallest precision possible.
405 ///
406 /// # Worst-case complexity
407 /// Constant time and additional memory.
408 ///
409 /// The number of significant bits of the raw mantissa must be divisible by the limb width. The
410 /// raw exponent must be in the range $[-(2^{30}-1), 2^{30}-1]$.
411 ///
412 /// # Worst-case complexity
413 /// Constant time and additional memory.
414 ///
415 /// # Panics
416 /// Panics if `raw_mantissa` is zero, if its number of significant bits is not divisible by the
417 /// limb width, or if `raw_exponent` is out of range.
418 ///
419 /// # Examples
420 /// ```
421 /// use malachite_base::num::arithmetic::traits::Pow;
422 /// use malachite_base::num::basic::integers::PrimitiveInt;
423 /// use malachite_base::num::conversion::traits::RawMantissaAndExponent;
424 /// use malachite_float::Float;
425 /// use malachite_nz::natural::Natural;
426 /// use malachite_nz::platform::Limb;
427 /// use malachite_q::Rational;
428 /// use std::str::FromStr;
429 ///
430 /// if Limb::WIDTH == u64::WIDTH {
431 /// assert_eq!(
432 /// <&Float as RawMantissaAndExponent<_, _, _>>::from_raw_mantissa_and_exponent(
433 /// Natural::from(9223372036854775808u64),
434 /// 1
435 /// ),
436 /// 1
437 /// );
438 /// assert_eq!(
439 /// <&Float as RawMantissaAndExponent<_, _, _>>::from_raw_mantissa_and_exponent(
440 /// Natural::from(14488038916154245120u64),
441 /// 2
442 /// ),
443 /// std::f64::consts::PI
444 /// );
445 /// assert_eq!(
446 /// <&Float as RawMantissaAndExponent<_, _, _>>::from_raw_mantissa_and_exponent(
447 /// Natural::from_str("202070319366191015160784900114134073344").unwrap(),
448 /// 80
449 /// ),
450 /// Natural::from(3u32).pow(50u64)
451 /// );
452 /// assert_eq!(
453 /// <&Float as RawMantissaAndExponent<_, _, _>>::from_raw_mantissa_and_exponent(
454 /// Natural::from_str("286514342137199872022965541161805021184").unwrap(),
455 /// -79
456 /// ),
457 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
458 /// );
459 /// }
460 /// ```
461 #[inline]
462 fn from_raw_mantissa_and_exponent(raw_mantissa: Natural, raw_exponent: i32) -> Float {
463 Float::from_raw_mantissa_and_exponent(raw_mantissa, raw_exponent)
464 }
465}
466
467impl IntegerMantissaAndExponent<Natural, i64> for Float {
468 /// Returns a [`Float`]'s integer mantissa and exponent, taking the [`Float`] by value.
469 ///
470 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
471 /// $m_i$ is an odd integer.
472 /// $$
473 /// f(x) = (\frac{|x|}{2^{e_i}}, e_i),
474 /// $$
475 /// where $e_i$ is the unique integer such that $x/2^{e_i}$ is an odd integer.
476 ///
477 /// The inverse operation is
478 /// [`from_integer_mantissa_and_exponent`](IntegerMantissaAndExponent::from_integer_mantissa_and_exponent).
479 ///
480 /// The integer exponent is less than or equal to $2^{30}-2$.
481 ///
482 /// # Worst-case complexity
483 /// $T(n) = O(n)$
484 ///
485 /// $M(n) = O(1)$
486 ///
487 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
488 ///
489 /// # Panics
490 /// Panics if `self` is zero or not finite.
491 ///
492 /// # Examples
493 /// ```
494 /// use malachite_base::num::arithmetic::traits::Pow;
495 /// use malachite_base::num::basic::traits::One;
496 /// use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
497 /// use malachite_float::Float;
498 /// use malachite_nz::natural::Natural;
499 /// use malachite_q::Rational;
500 /// use std::str::FromStr;
501 ///
502 /// assert_eq!(
503 /// Float::ONE.integer_mantissa_and_exponent(),
504 /// (Natural::ONE, 0)
505 /// );
506 /// assert_eq!(
507 /// Float::from(std::f64::consts::PI).integer_mantissa_and_exponent(),
508 /// (Natural::from(884279719003555u64), -48)
509 /// );
510 /// assert_eq!(
511 /// Float::exact_from(Natural::from(3u32).pow(50u64)).integer_mantissa_and_exponent(),
512 /// (Natural::from_str("717897987691852588770249").unwrap(), 0)
513 /// );
514 /// assert_eq!(
515 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
516 /// .0
517 /// .integer_mantissa_and_exponent(),
518 /// (
519 /// Natural::from_str("1067349099133908271875104088939").unwrap(),
520 /// -179
521 /// )
522 /// );
523 /// ```
524 fn integer_mantissa_and_exponent(self) -> (Natural, i64) {
525 if let Float(Finite {
526 exponent,
527 significand,
528 ..
529 }) = self
530 {
531 let zeros = significand.trailing_zeros().unwrap();
532 let shifted = significand >> zeros;
533 let bits = shifted.significant_bits();
534 (
535 shifted,
536 i64::exact_from(i128::from(exponent) - i128::from(bits)),
537 )
538 } else {
539 panic!()
540 }
541 }
542
543 /// Returns a [`Float`]'s integer exponent, taking the [`Float`] by value.
544 ///
545 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
546 /// $m_i$ is an odd integer.
547 /// $$
548 /// f(x) = e_i,
549 /// $$
550 /// where $e_i$ is the unique integer such that $x/2^{e_i}$ is an odd integer.
551 ///
552 /// The integer exponent is less than or equal to $2^{30}-2$.
553 ///
554 /// # Worst-case complexity
555 /// Constant time and additional memory.
556 ///
557 /// # Panics
558 /// Panics if `self` is zero or not finite.
559 ///
560 /// # Examples
561 /// ```
562 /// use malachite_base::num::arithmetic::traits::Pow;
563 /// use malachite_base::num::basic::traits::One;
564 /// use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
565 /// use malachite_float::Float;
566 /// use malachite_nz::natural::Natural;
567 /// use malachite_q::Rational;
568 ///
569 /// assert_eq!(Float::ONE.integer_exponent(), 0);
570 /// assert_eq!(Float::from(std::f64::consts::PI).integer_exponent(), -48);
571 /// assert_eq!(
572 /// Float::exact_from(Natural::from(3u32).pow(50u64)).integer_exponent(),
573 /// 0
574 /// );
575 /// assert_eq!(
576 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
577 /// .0
578 /// .integer_exponent(),
579 /// -179
580 /// );
581 /// ```
582 fn integer_exponent(self) -> i64 {
583 if let Float(Finite {
584 exponent,
585 significand,
586 ..
587 }) = self
588 {
589 i64::exact_from(
590 i128::from(exponent)
591 - i128::from(
592 significand.significant_bits() - significand.trailing_zeros().unwrap(),
593 ),
594 )
595 } else {
596 panic!()
597 }
598 }
599
600 /// Constructs a [`Float`] from its integer mantissa and exponent.
601 ///
602 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
603 /// $m_i$ is an odd integer.
604 ///
605 /// $$
606 /// f(x) = 2^{e_i}m_i.
607 /// $$
608 ///
609 /// The input does not have to be reduced; that is, the mantissa does not have to be odd. If the
610 /// inputs correspond to a number too large in absolute value or too close to zero to be
611 /// represented by a [`Float`], `None` is returned.
612 ///
613 /// # Worst-case complexity
614 /// $T(n) = O(n)$
615 ///
616 /// $M(n) = O(n)$
617 ///
618 /// where $T$ is time, $M$ is additional memory, and $n$ is
619 /// `integer_mantissa.significant_bits()`.
620 ///
621 /// # Examples
622 /// ```
623 /// use malachite_base::num::arithmetic::traits::Pow;
624 /// use malachite_base::num::basic::traits::One;
625 /// use malachite_base::num::conversion::traits::IntegerMantissaAndExponent;
626 /// use malachite_float::Float;
627 /// use malachite_nz::natural::Natural;
628 /// use malachite_q::Rational;
629 /// use std::str::FromStr;
630 ///
631 /// assert_eq!(
632 /// Float::from_integer_mantissa_and_exponent(Natural::ONE, 0).unwrap(),
633 /// 1
634 /// );
635 /// assert_eq!(
636 /// Float::from_integer_mantissa_and_exponent(Natural::from(884279719003555u64), -48)
637 /// .unwrap(),
638 /// std::f64::consts::PI
639 /// );
640 /// assert_eq!(
641 /// Float::from_integer_mantissa_and_exponent(
642 /// Natural::from_str("717897987691852588770249").unwrap(),
643 /// 0
644 /// )
645 /// .unwrap(),
646 /// Natural::from(3u32).pow(50u64)
647 /// );
648 /// assert_eq!(
649 /// Float::from_integer_mantissa_and_exponent(
650 /// Natural::from_str("1067349099133908271875104088939").unwrap(),
651 /// -179
652 /// )
653 /// .unwrap(),
654 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
655 /// );
656 /// ```
657 fn from_integer_mantissa_and_exponent(
658 integer_mantissa: Natural,
659 integer_exponent: i64,
660 ) -> Option<Float> {
661 let nonzero = integer_mantissa != 0u32;
662 let x = Float::exact_from(integer_mantissa) << integer_exponent;
663 if x.is_infinite() || (nonzero && x == 0) {
664 None
665 } else {
666 Some(x)
667 }
668 }
669}
670
671impl IntegerMantissaAndExponent<Natural, i64, Float> for &Float {
672 /// Returns a [`Float`]'s integer mantissa and exponent, taking the [`Float`] by reference.
673 ///
674 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
675 /// $m_i$ is an odd integer.
676 /// $$
677 /// f(x) = (\frac{|x|}{2^{e_i}}, e_i),
678 /// $$
679 /// where $e_i$ is the unique integer such that $x/2^{e_i}$ is an odd integer.
680 ///
681 /// The inverse operation is
682 /// [`from_integer_mantissa_and_exponent`](IntegerMantissaAndExponent::from_integer_mantissa_and_exponent).
683 ///
684 /// The integer exponent is less than or equal to $2^{30}-2$.
685 ///
686 /// # Worst-case complexity
687 /// $T(n) = O(n)$
688 ///
689 /// $M(n) = O(n)$
690 ///
691 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
692 ///
693 /// # Panics
694 /// Panics if `self` is zero or not finite.
695 ///
696 /// # Examples
697 /// ```
698 /// use malachite_base::num::arithmetic::traits::Pow;
699 /// use malachite_base::num::basic::traits::One;
700 /// use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
701 /// use malachite_float::Float;
702 /// use malachite_nz::natural::Natural;
703 /// use malachite_q::Rational;
704 /// use std::str::FromStr;
705 ///
706 /// assert_eq!(
707 /// (&Float::ONE).integer_mantissa_and_exponent(),
708 /// (Natural::ONE, 0)
709 /// );
710 /// assert_eq!(
711 /// (&Float::from(std::f64::consts::PI)).integer_mantissa_and_exponent(),
712 /// (Natural::from(884279719003555u64), -48)
713 /// );
714 /// assert_eq!(
715 /// (&Float::exact_from(Natural::from(3u32).pow(50u64))).integer_mantissa_and_exponent(),
716 /// (Natural::from_str("717897987691852588770249").unwrap(), 0)
717 /// );
718 /// assert_eq!(
719 /// (&Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0)
720 /// .integer_mantissa_and_exponent(),
721 /// (
722 /// Natural::from_str("1067349099133908271875104088939").unwrap(),
723 /// -179
724 /// )
725 /// );
726 /// ```
727 fn integer_mantissa_and_exponent(self) -> (Natural, i64) {
728 if let Float(Finite {
729 exponent,
730 significand,
731 ..
732 }) = self
733 {
734 let zeros = significand.trailing_zeros().unwrap();
735 let shifted = significand >> zeros;
736 let bits = shifted.significant_bits();
737 (
738 shifted,
739 i64::exact_from(i128::from(*exponent) - i128::from(bits)),
740 )
741 } else {
742 panic!()
743 }
744 }
745
746 /// Returns a [`Float`]'s integer exponent, taking the [`Float`] by reference.
747 ///
748 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
749 /// $m_i$ is an odd integer.
750 /// $$
751 /// f(x) = e_i,
752 /// $$
753 /// where $e_i$ is the unique integer such that $x/2^{e_i}$ is an odd integer.
754 ///
755 /// The integer exponent is less than or equal to $2^{30}-2$.
756 ///
757 /// # Worst-case complexity
758 /// Constant time and additional memory.
759 ///
760 /// # Panics
761 /// Panics if `self` is zero or not finite.
762 ///
763 /// # Examples
764 /// ```
765 /// use malachite_base::num::arithmetic::traits::Pow;
766 /// use malachite_base::num::basic::traits::One;
767 /// use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
768 /// use malachite_float::Float;
769 /// use malachite_nz::natural::Natural;
770 /// use malachite_q::Rational;
771 ///
772 /// assert_eq!((&Float::ONE).integer_exponent(), 0);
773 /// assert_eq!((&Float::from(std::f64::consts::PI)).integer_exponent(), -48);
774 /// assert_eq!(
775 /// (&Float::exact_from(Natural::from(3u32).pow(50u64))).integer_exponent(),
776 /// 0
777 /// );
778 /// assert_eq!(
779 /// (&Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0)
780 /// .integer_exponent(),
781 /// -179
782 /// );
783 /// ```
784 fn integer_exponent(self) -> i64 {
785 if let Float(Finite {
786 exponent,
787 significand,
788 ..
789 }) = self
790 {
791 i64::exact_from(
792 i128::from(*exponent)
793 - i128::from(
794 significand.significant_bits() - significand.trailing_zeros().unwrap(),
795 ),
796 )
797 } else {
798 panic!()
799 }
800 }
801
802 /// Constructs a [`Float`] from its integer mantissa and exponent.
803 ///
804 /// When $x$ is finite and nonzero, we can write $x = 2^{e_i}m_i$, where $e_i$ is an integer and
805 /// $m_i$ is an odd integer.
806 ///
807 /// $$
808 /// f(x) = 2^{e_i}m_i.
809 /// $$
810 ///
811 /// The input does not have to be reduced; that is, the mantissa does not have to be odd. If the
812 /// inputs correspond to a number too large in absolute value or too close to zero to be
813 /// represented by a [`Float`], `None` is returned.
814 ///
815 /// # Worst-case complexity
816 /// $T(n) = O(n)$
817 ///
818 /// $M(n) = O(n)$
819 ///
820 /// where $T$ is time, $M$ is additional memory, and $n$ is
821 /// `integer_mantissa.significant_bits()`.
822 ///
823 /// # Examples
824 /// ```
825 /// use malachite_base::num::arithmetic::traits::Pow;
826 /// use malachite_base::num::basic::traits::One;
827 /// use malachite_base::num::conversion::traits::IntegerMantissaAndExponent;
828 /// use malachite_float::Float;
829 /// use malachite_nz::natural::Natural;
830 /// use malachite_q::Rational;
831 /// use std::str::FromStr;
832 ///
833 /// assert_eq!(
834 /// <&Float as IntegerMantissaAndExponent<_, _, _>>::from_integer_mantissa_and_exponent(
835 /// Natural::ONE,
836 /// 0
837 /// )
838 /// .unwrap(),
839 /// 1
840 /// );
841 /// assert_eq!(
842 /// <&Float as IntegerMantissaAndExponent<_, _, _>>::from_integer_mantissa_and_exponent(
843 /// Natural::from(884279719003555u64),
844 /// -48
845 /// )
846 /// .unwrap(),
847 /// std::f64::consts::PI
848 /// );
849 /// assert_eq!(
850 /// <&Float as IntegerMantissaAndExponent<_, _, _>>::from_integer_mantissa_and_exponent(
851 /// Natural::from_str("717897987691852588770249").unwrap(),
852 /// 0
853 /// )
854 /// .unwrap(),
855 /// Natural::from(3u32).pow(50u64)
856 /// );
857 /// assert_eq!(
858 /// <&Float as IntegerMantissaAndExponent<_, _, _>>::from_integer_mantissa_and_exponent(
859 /// Natural::from_str("1067349099133908271875104088939").unwrap(),
860 /// -179
861 /// )
862 /// .unwrap(),
863 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
864 /// );
865 /// ```
866 #[inline]
867 fn from_integer_mantissa_and_exponent(
868 integer_mantissa: Natural,
869 integer_exponent: i64,
870 ) -> Option<Float> {
871 Float::from_integer_mantissa_and_exponent(integer_mantissa, integer_exponent)
872 }
873}
874
875impl SciMantissaAndExponent<Float, i32> for Float {
876 /// Returns a [`Float`]'s scientific mantissa and exponent, taking the [`Float`] by value.
877 ///
878 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
879 /// and $m_s$ is a rational number with $1 \leq m_s < 2$. We represent the rational mantissa as
880 /// a [`Float`].
881 /// $$
882 /// f(x) = (\frac{|x|}{2^{\lfloor \log_2 |x| \rfloor}}, \lfloor \log_2 |x| \rfloor).
883 /// $$
884 ///
885 /// The returned exponent is always in the range $[-2^{30}, 2^{30}-2]$.
886 ///
887 /// # Worst-case complexity
888 /// Constant time and additional memory.
889 ///
890 /// # Panics
891 /// Panics if `self` is zero or not finite.
892 ///
893 /// # Examples
894 /// ```
895 /// use malachite_base::num::arithmetic::traits::Pow;
896 /// use malachite_base::num::basic::traits::One;
897 /// use malachite_base::num::conversion::traits::{ExactFrom, SciMantissaAndExponent};
898 /// use malachite_float::Float;
899 /// use malachite_nz::natural::Natural;
900 /// use malachite_q::Rational;
901 ///
902 /// assert_eq!(Float::ONE.sci_mantissa_and_exponent(), (Float::ONE, 0));
903 ///
904 /// let (m, e) = Float::from(std::f64::consts::PI).sci_mantissa_and_exponent();
905 /// assert_eq!(m.to_string(), "1.570796326794897");
906 /// assert_eq!(e, 1);
907 ///
908 /// let (m, e) = Float::exact_from(Natural::from(3u32).pow(50u64)).sci_mantissa_and_exponent();
909 /// assert_eq!(m.to_string(), "1.187662594419065093441695");
910 /// assert_eq!(e, 79);
911 ///
912 /// let (m, e) = Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
913 /// .0
914 /// .sci_mantissa_and_exponent();
915 /// assert_eq!(m.to_string(), "1.683979953059212693885095551367");
916 /// assert_eq!(e, -80);
917 /// ```
918 #[inline]
919 fn sci_mantissa_and_exponent(mut self) -> (Float, i32) {
920 if let Float(Finite { sign, exponent, .. }) = &mut self {
921 let old_exponent = *exponent;
922 *exponent = 1;
923 *sign = true;
924 (self, old_exponent - 1)
925 } else {
926 panic!()
927 }
928 }
929
930 /// Returns a [`Float`]'s scientific exponent, taking the [`Float`] by value.
931 ///
932 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
933 /// and $m_s$ is a rational number with $1 \leq m_s < 2$.
934 /// $$
935 /// f(x) = \lfloor \log_2 |x| \rfloor.
936 /// $$
937 ///
938 /// The returned exponent is always in the range $[-2^{30}, 2^{30}-2]$.
939 ///
940 /// # Worst-case complexity
941 /// Constant time and additional memory.
942 ///
943 /// # Panics
944 /// Panics if `self` is zero or not finite.
945 ///
946 /// # Examples
947 /// ```
948 /// use malachite_base::num::arithmetic::traits::Pow;
949 /// use malachite_base::num::basic::traits::One;
950 /// use malachite_base::num::conversion::traits::{ExactFrom, SciMantissaAndExponent};
951 /// use malachite_float::Float;
952 /// use malachite_nz::natural::Natural;
953 /// use malachite_q::Rational;
954 ///
955 /// assert_eq!(Float::ONE.sci_exponent(), 0);
956 /// assert_eq!(Float::from(std::f64::consts::PI).sci_exponent(), 1);
957 /// assert_eq!(
958 /// Float::exact_from(Natural::from(3u32).pow(50u64)).sci_exponent(),
959 /// 79
960 /// );
961 /// assert_eq!(
962 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100)
963 /// .0
964 /// .sci_exponent(),
965 /// -80
966 /// );
967 /// ```
968 #[inline]
969 fn sci_exponent(self) -> i32 {
970 self.raw_exponent() - 1
971 }
972
973 /// Constructs a [`Float`] from its scientific mantissa and exponent.
974 ///
975 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
976 /// and $m_s$ is a rational number with $1 \leq m_s < 2$.
977 ///
978 /// $$
979 /// f(x) = 2^{e_i}m_i.
980 /// $$
981 ///
982 /// If the mantissa is zero or not finite, this function panics. If it is finite but not in the
983 /// interval $[1, 2)$, `None` is returned. If the inputs correspond to a number too large in
984 /// absolute value or too close to zero to be represented by a [`Float`], `None` is returned.
985 ///
986 /// # Worst-case complexity
987 /// Constant time and additional memory.
988 ///
989 /// # Examples
990 /// ```
991 /// use malachite_base::num::arithmetic::traits::Pow;
992 /// use malachite_base::num::basic::traits::One;
993 /// use malachite_base::num::conversion::traits::{FromStringBase, SciMantissaAndExponent};
994 /// use malachite_float::Float;
995 /// use malachite_nz::natural::Natural;
996 /// use malachite_q::Rational;
997 ///
998 /// assert_eq!(
999 /// Float::from_sci_mantissa_and_exponent(Float::ONE, 0).unwrap(),
1000 /// 1
1001 /// );
1002 /// assert_eq!(
1003 /// Float::from_sci_mantissa_and_exponent(
1004 /// Float::from_string_base(16, "0x1.921fb54442d18#53").unwrap(),
1005 /// 1
1006 /// )
1007 /// .unwrap(),
1008 /// std::f64::consts::PI
1009 /// );
1010 /// assert_eq!(
1011 /// Float::from_sci_mantissa_and_exponent(
1012 /// Float::from_string_base(16, "0x1.300aa7e1b65fa13bc792#80").unwrap(),
1013 /// 79
1014 /// )
1015 /// .unwrap(),
1016 /// Natural::from(3u32).pow(50u64)
1017 /// );
1018 /// assert_eq!(
1019 /// Float::from_sci_mantissa_and_exponent(
1020 /// Float::from_string_base(16, "0x1.af194f6982497a23f9dc546d6#100").unwrap(),
1021 /// -80
1022 /// )
1023 /// .unwrap(),
1024 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
1025 /// );
1026 /// ```
1027 fn from_sci_mantissa_and_exponent(mut sci_mantissa: Float, sci_exponent: i32) -> Option<Float> {
1028 assert!(sci_mantissa.is_finite());
1029 assert!(!sci_mantissa.is_zero());
1030 if sci_mantissa.is_sign_negative()
1031 || (&sci_mantissa).raw_exponent() != 1
1032 || !(Float::MIN_EXPONENT - 1..=Float::MAX_EXPONENT - 1).contains(&sci_exponent)
1033 {
1034 return None;
1035 }
1036 if let Float(Finite { exponent, .. }) = &mut sci_mantissa {
1037 *exponent = sci_exponent + 1;
1038 } else {
1039 panic!()
1040 }
1041 Some(sci_mantissa)
1042 }
1043}
1044
1045impl SciMantissaAndExponent<Float, i32, Float> for &Float {
1046 /// Returns a [`Float`]'s scientific mantissa and exponent, taking the [`Float`] by reference.
1047 ///
1048 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
1049 /// and $m_s$ is a rational number with $1 \leq m_s < 2$. We represent the rational mantissa as
1050 /// a [`Float`].
1051 /// $$
1052 /// f(x) = (\frac{|x|}{2^{\lfloor \log_2 |x| \rfloor}}, \lfloor \log_2 |x| \rfloor).
1053 /// $$
1054 ///
1055 /// The returned exponent is always in the range $[-2^{30}, 2^{30}-2]$.
1056 ///
1057 /// # Worst-case complexity
1058 /// $T(n) = O(n)$
1059 ///
1060 /// $M(n) = O(n)$
1061 ///
1062 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
1063 ///
1064 /// # Panics
1065 /// Panics if `self` is zero or not finite.
1066 ///
1067 /// # Examples
1068 /// ```
1069 /// use malachite_base::num::arithmetic::traits::Pow;
1070 /// use malachite_base::num::basic::traits::One;
1071 /// use malachite_base::num::conversion::traits::{ExactFrom, SciMantissaAndExponent};
1072 /// use malachite_float::Float;
1073 /// use malachite_nz::natural::Natural;
1074 /// use malachite_q::Rational;
1075 ///
1076 /// assert_eq!((&Float::ONE).sci_mantissa_and_exponent(), (Float::ONE, 0));
1077 ///
1078 /// let (m, e): (Float, i32) = (&Float::from(std::f64::consts::PI)).sci_mantissa_and_exponent();
1079 /// assert_eq!(m.to_string(), "1.570796326794897");
1080 /// assert_eq!(e, 1);
1081 ///
1082 /// let (m, e): (Float, i32) =
1083 /// (&Float::exact_from(Natural::from(3u32).pow(50u64))).sci_mantissa_and_exponent();
1084 /// assert_eq!(m.to_string(), "1.187662594419065093441695");
1085 /// assert_eq!(e, 79);
1086 ///
1087 /// let (m, e): (Float, i32) =
1088 /// (&Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0)
1089 /// .sci_mantissa_and_exponent();
1090 /// assert_eq!(m.to_string(), "1.683979953059212693885095551367");
1091 /// assert_eq!(e, -80);
1092 /// ```
1093 #[inline]
1094 fn sci_mantissa_and_exponent(self) -> (Float, i32) {
1095 if let Float(Finite {
1096 exponent,
1097 precision,
1098 significand,
1099 ..
1100 }) = self
1101 {
1102 (
1103 Float(Finite {
1104 sign: true,
1105 exponent: 1,
1106 precision: *precision,
1107 significand: significand.clone(),
1108 }),
1109 exponent - 1,
1110 )
1111 } else {
1112 panic!()
1113 }
1114 }
1115
1116 /// Returns a [`Float`]'s scientific exponent, taking the [`Float`] by reference.
1117 ///
1118 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
1119 /// and $m_s$ is a rational number with $1 \leq m_s < 2$.
1120 /// $$
1121 /// f(x) = \lfloor \log_2 |x| \rfloor.
1122 /// $$
1123 ///
1124 /// The returned exponent is always in the range $[-2^{30}, 2^{30}-2]$.
1125 ///
1126 /// # Worst-case complexity
1127 /// Constant time and additional memory.
1128 ///
1129 /// # Panics
1130 /// Panics if `self` is zero or not finite.
1131 ///
1132 /// # Examples
1133 /// ```
1134 /// use malachite_base::num::arithmetic::traits::Pow;
1135 /// use malachite_base::num::basic::traits::One;
1136 /// use malachite_base::num::conversion::traits::{ExactFrom, SciMantissaAndExponent};
1137 /// use malachite_float::Float;
1138 /// use malachite_nz::natural::Natural;
1139 /// use malachite_q::Rational;
1140 ///
1141 /// assert_eq!(
1142 /// <&Float as SciMantissaAndExponent<Float, _, _>>::sci_exponent(&Float::ONE),
1143 /// 0
1144 /// );
1145 /// assert_eq!(
1146 /// <&Float as SciMantissaAndExponent<Float, _, _>>::sci_exponent(&Float::from(
1147 /// std::f64::consts::PI
1148 /// )),
1149 /// 1
1150 /// );
1151 /// assert_eq!(
1152 /// <&Float as SciMantissaAndExponent<Float, _, _>>::sci_exponent(&Float::exact_from(
1153 /// Natural::from(3u32).pow(50u64)
1154 /// )),
1155 /// 79
1156 /// );
1157 /// assert_eq!(
1158 /// <&Float as SciMantissaAndExponent<Float, _, _>>::sci_exponent(
1159 /// &Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
1160 /// ),
1161 /// -80
1162 /// );
1163 /// ```
1164 #[inline]
1165 fn sci_exponent(self) -> i32 {
1166 self.raw_exponent() - 1
1167 }
1168
1169 /// Constructs a [`Float`] from its scientific mantissa and exponent.
1170 ///
1171 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an integer
1172 /// and $m_s$ is a rational number with $1 \leq m_s < 2$.
1173 ///
1174 /// $$
1175 /// f(x) = 2^{e_i}m_i.
1176 /// $$
1177 ///
1178 /// If the mantissa is zero or not finite, this function panics. If it is finite but not in the
1179 /// interval $[1, 2)$, this function returns `None`.
1180 ///
1181 /// If the mantissa is zero or not finite, this function panics. If it is finite but not in the
1182 /// interval $[1, 2)$, `None` is returned. If the inputs correspond to a number too large in
1183 /// absolute value or too close to zero to be represented by a [`Float`], `None` is returned.
1184 ///
1185 /// # Worst-case complexity
1186 /// Constant time and additional memory.
1187 ///
1188 /// # Examples
1189 /// ```
1190 /// use malachite_base::num::arithmetic::traits::Pow;
1191 /// use malachite_base::num::basic::traits::One;
1192 /// use malachite_base::num::conversion::traits::{FromStringBase, SciMantissaAndExponent};
1193 /// use malachite_float::Float;
1194 /// use malachite_nz::natural::Natural;
1195 /// use malachite_q::Rational;
1196 ///
1197 /// assert_eq!(
1198 /// Float::from_sci_mantissa_and_exponent(Float::ONE, 0).unwrap(),
1199 /// 1
1200 /// );
1201 /// assert_eq!(
1202 /// <&Float as SciMantissaAndExponent<Float, _, _>>::from_sci_mantissa_and_exponent(
1203 /// Float::from_string_base(16, "0x1.921fb54442d18#53").unwrap(),
1204 /// 1
1205 /// )
1206 /// .unwrap(),
1207 /// std::f64::consts::PI
1208 /// );
1209 /// assert_eq!(
1210 /// <&Float as SciMantissaAndExponent<Float, _, _>>::from_sci_mantissa_and_exponent(
1211 /// Float::from_string_base(16, "0x1.300aa7e1b65fa13bc792#80").unwrap(),
1212 /// 79
1213 /// )
1214 /// .unwrap(),
1215 /// Natural::from(3u32).pow(50u64)
1216 /// );
1217 /// assert_eq!(
1218 /// <&Float as SciMantissaAndExponent<Float, _, _>>::from_sci_mantissa_and_exponent(
1219 /// Float::from_string_base(16, "0x1.af194f6982497a23f9dc546d6#100").unwrap(),
1220 /// -80
1221 /// )
1222 /// .unwrap(),
1223 /// Float::from_rational_prec(Rational::from(3u32).pow(-50i64), 100).0
1224 /// );
1225 /// ```
1226 #[inline]
1227 fn from_sci_mantissa_and_exponent(sci_mantissa: Float, sci_exponent: i32) -> Option<Float> {
1228 Float::from_sci_mantissa_and_exponent(sci_mantissa, sci_exponent)
1229 }
1230}
1231
1232macro_rules! impl_mantissa_and_exponent {
1233 ($t:ident) => {
1234 impl SciMantissaAndExponent<$t, i32, Float> for &Float {
1235 /// Returns a [`Float`]'s scientific mantissa and exponent, taking the [`Float`] by
1236 /// value.
1237 ///
1238 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an
1239 /// integer and $m_s$ is a rational number with $1 \leq m_s < 2$. We represent the
1240 /// rational mantissa as a primitive float. The conversion might not be exact, so we
1241 /// round to the nearest float using the `Nearest` rounding mode. To use other rounding
1242 /// modes, use
1243 /// [`sci_mantissa_and_exponent_round`](Float::sci_mantissa_and_exponent_round).
1244 /// $$
1245 /// f(x) \approx (\frac{|x|}{2^{\lfloor \log_2 |x| \rfloor}},
1246 /// \lfloor \log_2 |x| \rfloor).
1247 /// $$
1248 ///
1249 /// The returned exponent is always in the range $[-2^{30}, 2^{30}-2]$.
1250 ///
1251 /// # Worst-case complexity
1252 /// $T(n) = O(n)$
1253 ///
1254 /// $M(n) = O(1)$
1255 ///
1256 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
1257 ///
1258 /// # Panics
1259 /// Panics if `self` is zero or not finite.
1260 ///
1261 /// # Examples
1262 /// See [here](super::mantissa_and_exponent#sci_mantissa_and_exponent).
1263 #[inline]
1264 fn sci_mantissa_and_exponent(self) -> ($t, i32) {
1265 let (m, e, _) = self.sci_mantissa_and_exponent_round(Nearest).unwrap();
1266 (m, e)
1267 }
1268
1269 /// Constructs a [`Float`] from its scientific mantissa and exponent.
1270 ///
1271 /// When $x$ is finite and nonzero, we can write $|x| = 2^{e_s}m_s$, where $e_s$ is an
1272 /// integer and $m_s$ is a rational number with $1 \leq m_s < 2$.
1273 ///
1274 /// $$
1275 /// f(x) = 2^{e_i}m_i.
1276 /// $$
1277 ///
1278 /// If the mantissa is zero or not finite, this function panics. If it is finite but not
1279 /// in the interval $[1, 2)$, `None` is returned. If the inputs correspond to a number
1280 /// too large in absolute value or too close to zero to be represented by a [`Float`],
1281 /// `None` is returned.
1282 ///
1283 /// # Worst-case complexity
1284 /// Constant time and additional memory.
1285 ///
1286 /// # Examples
1287 /// See [here](super::mantissa_and_exponent#from_sci_mantissa_and_exponent).
1288 #[allow(clippy::manual_range_contains)]
1289 #[inline]
1290 fn from_sci_mantissa_and_exponent(
1291 sci_mantissa: $t,
1292 sci_exponent: i32,
1293 ) -> Option<Float> {
1294 assert!(sci_mantissa.is_finite());
1295 assert_ne!(sci_mantissa, 0.0);
1296 if sci_mantissa < 1.0
1297 || sci_mantissa >= 2.0
1298 || sci_exponent > Float::MAX_EXPONENT - 1
1299 || sci_exponent < Float::MIN_EXPONENT - 1
1300 {
1301 None
1302 } else {
1303 let m = sci_mantissa.integer_mantissa();
1304 (Float::from(m)
1305 << (i128::from(sci_exponent) - i128::from(m.significant_bits()) + 1))
1306 .to_finite()
1307 }
1308 }
1309 }
1310 };
1311}
1312apply_to_primitive_floats!(impl_mantissa_and_exponent);