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