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