malachite_float/
lib.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9//! This crate defines [`Float`]s, which are arbitrary-precision floating-point numbers.
10//!
11//! [`Float`]s are currently experimental. They are missing many important functions. However, the
12//! functions that are currently implemented are thoroughly tested and documented, with the
13//! exception of string conversion functions. The current string conversions are incomplete and
14//! will be changed in the future to match MPFR's behavior.
15//!
16//! # Demos and benchmarks
17//! This crate comes with a `bin` target that can be used for running demos and benchmarks.
18//! - Almost all of the public functions in this crate have an associated demo. Running a demo
19//!   shows you a function's behavior on a large number of inputs. TODO
20//! - You can use a similar command to run benchmarks. TODO
21//!
22//! The list of available demos and benchmarks is not documented anywhere; you must find them by
23//! browsing through
24//! [`bin_util/demo_and_bench`](https://github.com/mhogrefe/malachite/tree/master/malachite-float/src/bin_util/demo_and_bench).
25//!
26//! # Features
27//! - `32_bit_limbs`: Sets the type of [`Limb`](malachite_nz#limbs) to [`u32`] instead of the
28//!   default, [`u64`].
29//! - `test_build`: A large proportion of the code in this crate is only used for testing. For a
30//!   typical user, building this code would result in an unnecessarily long compilation time and
31//!   an unnecessarily large binary. My solution is to only build this code when the `test_build`
32//!   feature is enabled. If you want to run unit tests, you must enable `test_build`. However,
33//!   doctests don't require it, since they only test the public interface.
34//! - `bin_build`: This feature is used to build the code for demos and benchmarks, which also
35//!   takes a long time to build. Enabling this feature also enables `test_build`.
36
37#![allow(
38    unstable_name_collisions,
39    clippy::assertions_on_constants,
40    clippy::cognitive_complexity,
41    clippy::many_single_char_names,
42    clippy::range_plus_one,
43    clippy::suspicious_arithmetic_impl,
44    clippy::suspicious_op_assign_impl,
45    clippy::too_many_arguments,
46    clippy::type_complexity,
47    clippy::upper_case_acronyms,
48    clippy::multiple_bound_locations
49)]
50#![warn(
51    clippy::cast_lossless,
52    clippy::explicit_into_iter_loop,
53    clippy::explicit_iter_loop,
54    clippy::filter_map_next,
55    clippy::large_digit_groups,
56    clippy::manual_filter_map,
57    clippy::manual_find_map,
58    clippy::map_flatten,
59    clippy::map_unwrap_or,
60    clippy::match_same_arms,
61    clippy::missing_const_for_fn,
62    clippy::mut_mut,
63    clippy::needless_borrow,
64    clippy::needless_continue,
65    clippy::needless_pass_by_value,
66    clippy::print_stdout,
67    clippy::redundant_closure_for_method_calls,
68    clippy::single_match_else,
69    clippy::trait_duplication_in_bounds,
70    clippy::type_repetition_in_bounds,
71    clippy::uninlined_format_args,
72    clippy::unused_self,
73    clippy::if_not_else,
74    clippy::manual_assert,
75    clippy::range_plus_one,
76    clippy::redundant_else,
77    clippy::semicolon_if_nothing_returned,
78    clippy::cloned_instead_of_copied,
79    clippy::flat_map_option,
80    clippy::unnecessary_wraps,
81    clippy::unnested_or_patterns,
82    clippy::trivially_copy_pass_by_ref
83)]
84#![cfg_attr(not(any(feature = "test_build", feature = "random")), no_std)]
85
86extern crate alloc;
87
88#[macro_use]
89extern crate malachite_base;
90
91#[cfg(feature = "test_build")]
92extern crate itertools;
93
94#[cfg(feature = "test_build")]
95use crate::InnerFloat::Finite;
96use core::ops::Deref;
97#[cfg(feature = "test_build")]
98use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2;
99use malachite_base::num::basic::integers::PrimitiveInt;
100#[cfg(feature = "test_build")]
101use malachite_base::num::logic::traits::SignificantBits;
102use malachite_nz::natural::Natural;
103use malachite_nz::platform::Limb;
104
105/// A floating-point number.
106///
107/// `Float`s are currently experimental. They are missing many important functions. However, the
108/// functions that are currently implemented are thoroughly tested and documented, with the
109/// exception of string conversion functions. The current string conversions are incomplete and will
110/// be changed in the future to match MPFR's behavior.
111///
112/// `Float`s are similar to the primitive floats defined by the IEEE 754 standard. They include NaN,
113/// positive and $-\infty$, and positive and negative zero. There is only one NaN; there is no
114/// concept of a NaN payload.
115///
116/// All the finite `Float`s are dyadic rationals (rational numbers whose denominator is a power of
117/// 2). A finite `Float` consists of several fields:
118/// - a sign, which denotes whether the `Float` is positive or negative;
119/// - a significand, which is a [`Natural`] number whose value is equal to the `Float`'s absolute
120///   value multiplied by a power of 2;
121/// - an exponent, which is one more than the floor of the base-2 logarithm of the `Float`'s
122///   absolute value;
123/// - and finally, a precision, which is greater than zero and indicates the number of significant
124///   bits. It is common to think of a `Float` as an approximation to some real number, and the
125///   precision indicates how good the approximation is intended to be.
126///
127/// `Float`s inherit some odd behavior from the IEEE 754 standard regarding comparison. A `NaN` is
128/// not equal to any `Float`, including itself. Positive and negative zero compare as equal, despite
129/// being two distinct values. Additionally, (and this is not IEEE 754's fault), `Float`s with
130/// different precisions compare as equal if they represent the same numeric value.
131///
132/// In many cases, the above behavior is unsatisfactory, so the [`ComparableFloat`] and
133/// [`ComparableFloat`] wrappers are provided. See their documentation for a description of their
134/// comparison behavior.
135///
136/// In documentation, we will use the '$=$' sign to mean that two `Float`s are identical, writing
137/// things like $-\text{NaN}=\text{NaN}$ and $-(0.0) = -0.0$.
138///
139/// The `Float` type is designed to be very similar to the `mpfr_t` type in
140/// [MPFR](https://www.mpfr.org/mpfr-current/mpfr.html#Nomenclature-and-Types), and all Malachite
141/// functions produce exactly the same result as their counterparts in MPFR, unless otherwise noted.
142///
143/// Here are the structural difference between `Float` and `mpfr_t`:
144/// - `Float` can only represent a single `NaN` value, with no sign or payload.
145/// - Only finite, nonzero `Float`s have a significand, precision, and exponent. For other `Float`s,
146///   these concepts are undefined. In particular, unlike `mpfr_t` zeros, `Float` zeros do not have
147///   a precision.
148/// - The types of `mpfr_t` components are configuration- and platform-dependent. The types of
149///   `Float` components are platform-independent, although the `Limb` type is
150///   configuration-dependent: it is `u64` by default, but may be changed to `u32` using the
151///   `--32_bit_limbs` compiler flag. The type of the exponent is always `i32` and the type of the
152///   precision is always `u64`. The `Limb` type only has a visible effect on the functions that
153///   extract the raw significand. All other functions have the same interface when compiled with
154///   either `Limb` type.
155///
156/// `Float`s whose precision is 64 bits or less can be represented without any memory allocation.
157/// (Unless Malachite is compiled with `32_bit_limbs`, in which case the limit is 32).
158#[derive(Clone)]
159pub struct Float(pub(crate) InnerFloat);
160
161// We want to limit the visibility of the `NaN`, `Zero`, `Infinity`, and `Finite` constructors to
162// within this crate. To do this, we wrap the `InnerFloat` enum in a struct that gets compiled away.
163#[derive(Clone)]
164pub(crate) enum InnerFloat {
165    NaN,
166    Infinity {
167        sign: bool,
168    },
169    Zero {
170        sign: bool,
171    },
172    Finite {
173        sign: bool,
174        exponent: i32,
175        precision: u64,
176        significand: Natural,
177    },
178}
179
180#[inline]
181pub(crate) fn significand_bits(significand: &Natural) -> u64 {
182    significand.limb_count() << Limb::LOG_WIDTH
183}
184
185impl Float {
186    /// The maximum raw exponent of any [`Float`], equal to $2^{30}-1$, or $1,073,741,823$. This is
187    /// one more than the maximum scientific exponent. If we write a [`Float`] as $\pm m2^e$, with
188    /// $1\leq m<2$ and $e$ an integer, we must have $e\leq 2^{30}-2$. If the result of a
189    /// calculation would produce a [`Float`] with an exponent larger than this, $\pm\infty$ is
190    /// returned instead.
191    pub const MAX_EXPONENT: i32 = 0x3fff_ffff;
192    /// The minimum raw exponent of any [`Float`], equal to $-(2^{30}-1)$, or $-1,073,741,823$. This
193    /// is one more than the minimum scientific exponent. If we write a [`Float`] as $\pm m2^e$,
194    /// with $1\leq m<2$ and $e$ an integer, we must have $e\geq -2^{30}$. If the result of a
195    /// calculation would produce a [`Float`] with an exponent smaller than this, $\pm0.0$ is
196    /// returned instead.
197    pub const MIN_EXPONENT: i32 = -Float::MAX_EXPONENT;
198
199    #[cfg(feature = "test_build")]
200    pub fn is_valid(&self) -> bool {
201        match self {
202            Float(Finite {
203                precision,
204                significand,
205                exponent,
206                ..
207            }) => {
208                if *precision == 0
209                    || !significand.is_valid()
210                    || *exponent > Float::MAX_EXPONENT
211                    || *exponent < Float::MIN_EXPONENT
212                {
213                    return false;
214                }
215                let bits = significand.significant_bits();
216                bits != 0
217                    && bits.divisible_by_power_of_2(Limb::LOG_WIDTH)
218                    && *precision <= bits
219                    && bits - precision < Limb::WIDTH
220                    && significand.divisible_by_power_of_2(bits - precision)
221            }
222            _ => true,
223        }
224    }
225}
226
227/// `ComparableFloat` is a wrapper around a [`Float`], taking the [`Float`] by value.
228///
229/// `CompatableFloat` has different comparison behavior than [`Float`]. See the [`Float`]
230/// documentation for its comparison behavior, which is largely derived from the IEEE 754
231/// specification; the `ComparableFloat` behavior, on the other hand, is more mathematically
232/// well-behaved, and respects the principle that equality should be the finest equivalence
233/// relation: that is, that two equal objects should not be different in any way.
234///
235/// To be more specific: when a [`Float`] is wrapped in a `ComparableFloat`,
236/// - `NaN` is not equal to any other [`Float`], but equal to itself;
237/// - Positive and negative zero are not equal to each other;
238/// - Ordering is total. Negative zero is ordered to be smaller than positive zero, and `NaN` is
239///   arbitrarily ordered to be between the two zeros;
240/// - Two [`Float`]s with different precisions but representing the same value are unequal, and the
241///   one with the greater precision is ordered to be larger;
242/// - The hashing function is compatible with equality.
243///
244/// The analogous wrapper for primitive floats is
245/// [`NiceFloat`](malachite_base::num::float::NiceFloat). However,
246/// [`NiceFloat`](malachite_base::num::float::NiceFloat) also facilitates better string conversion,
247/// something that isn't necessary for [`Float`]s
248///
249/// `ComparableFloat` owns its float. This is useful in many cases, for example if you want to use
250/// [`Float`]s as keys in a hash map. In other situations, it is better to use
251/// [`ComparableFloatRef`], which only has a reference to its float.
252#[derive(Clone)]
253pub struct ComparableFloat(pub Float);
254
255/// `ComparableFloatRef` is a wrapper around a [`Float`], taking the [`Float`] be reference.
256///
257/// See the [`ComparableFloat`] documentation for details.
258#[derive(Clone)]
259pub struct ComparableFloatRef<'a>(pub &'a Float);
260
261impl ComparableFloat {
262    pub const fn as_ref(&self) -> ComparableFloatRef {
263        ComparableFloatRef(&self.0)
264    }
265}
266
267impl Deref for ComparableFloat {
268    type Target = Float;
269
270    /// Allows a [`ComparableFloat`] to dereference to a [`Float`].
271    ///
272    /// ```
273    /// use malachite_base::num::basic::traits::One;
274    /// use malachite_float::{ComparableFloat, Float};
275    ///
276    /// let x = ComparableFloat(Float::ONE);
277    /// assert_eq!(*x, Float::ONE);
278    /// ```
279    fn deref(&self) -> &Float {
280        &self.0
281    }
282}
283
284impl Deref for ComparableFloatRef<'_> {
285    type Target = Float;
286
287    /// Allows a [`ComparableFloatRef`] to dereference to a [`Float`].
288    ///
289    /// ```
290    /// use malachite_base::num::basic::traits::One;
291    /// use malachite_float::{ComparableFloatRef, Float};
292    ///
293    /// let x = Float::ONE;
294    /// let y = ComparableFloatRef(&x);
295    /// assert_eq!(*y, Float::ONE);
296    /// ```
297    fn deref(&self) -> &Float {
298        self.0
299    }
300}
301
302/// Traits for arithmetic.
303pub mod arithmetic;
304#[macro_use]
305/// Basic traits for working with [`Float`]s.
306pub mod basic;
307/// Traits for comparing [`Float`]s for equality or order.
308pub mod comparison;
309/// Functions that produce [`Float`] approximations of mathematical constants, using a given
310/// precision and rounding mode.
311pub mod constants;
312/// Traits for converting to and from [`Float`]s, including converting [`Float`]s to and from
313/// strings.
314pub mod conversion;
315/// Iterators that generate [`Float`]s without repetition.
316pub mod exhaustive;
317#[cfg(feature = "random")]
318/// Iterators that generate [`Float`]s randomly.
319pub mod random;
320
321#[cfg(feature = "test_build")]
322pub mod test_util;