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(
85    not(any(feature = "test_build", feature = "random", feature = "std")),
86    no_std
87)]
88
89extern crate alloc;
90
91#[macro_use]
92extern crate malachite_base;
93
94#[cfg(feature = "test_build")]
95extern crate itertools;
96
97#[cfg(feature = "test_build")]
98use crate::InnerFloat::Finite;
99use core::ops::Deref;
100#[cfg(feature = "test_build")]
101use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2;
102use malachite_base::num::basic::integers::PrimitiveInt;
103#[cfg(feature = "test_build")]
104use malachite_base::num::logic::traits::SignificantBits;
105use malachite_nz::natural::Natural;
106use malachite_nz::platform::Limb;
107
108/// A floating-point number.
109///
110/// `Float`s are currently experimental. They are missing many important functions. However, the
111/// functions that are currently implemented are thoroughly tested and documented, with the
112/// exception of string conversion functions. The current string conversions are incomplete and will
113/// be changed in the future to match MPFR's behavior.
114///
115/// `Float`s are similar to the primitive floats defined by the IEEE 754 standard. They include NaN,
116/// positive and $-\infty$, and positive and negative zero. There is only one NaN; there is no
117/// concept of a NaN payload.
118///
119/// All the finite `Float`s are dyadic rationals (rational numbers whose denominator is a power of
120/// 2). A finite `Float` consists of several fields:
121/// - a sign, which denotes whether the `Float` is positive or negative;
122/// - a significand, which is a [`Natural`] number whose value is equal to the `Float`'s absolute
123///   value multiplied by a power of 2;
124/// - an exponent, which is one more than the floor of the base-2 logarithm of the `Float`'s
125///   absolute value;
126/// - and finally, a precision, which is greater than zero and indicates the number of significant
127///   bits. It is common to think of a `Float` as an approximation to some real number, and the
128///   precision indicates how good the approximation is intended to be.
129///
130/// `Float`s inherit some odd behavior from the IEEE 754 standard regarding comparison. A `NaN` is
131/// not equal to any `Float`, including itself. Positive and negative zero compare as equal, despite
132/// being two distinct values. Additionally, (and this is not IEEE 754's fault), `Float`s with
133/// different precisions compare as equal if they represent the same numeric value.
134///
135/// In many cases, the above behavior is unsatisfactory, so the [`ComparableFloat`] and
136/// [`ComparableFloat`] wrappers are provided. See their documentation for a description of their
137/// comparison behavior.
138///
139/// In documentation, we will use the '$=$' sign to mean that two `Float`s are identical, writing
140/// things like $-\text{NaN}=\text{NaN}$ and $-(0.0) = -0.0$.
141///
142/// The `Float` type is designed to be very similar to the `mpfr_t` type in
143/// [MPFR](https://www.mpfr.org/mpfr-current/mpfr.html#Nomenclature-and-Types), and all Malachite
144/// functions produce exactly the same result as their counterparts in MPFR, unless otherwise noted.
145///
146/// Here are the structural difference between `Float` and `mpfr_t`:
147/// - `Float` can only represent a single `NaN` value, with no sign or payload.
148/// - Only finite, nonzero `Float`s have a significand, precision, and exponent. For other `Float`s,
149///   these concepts are undefined. In particular, unlike `mpfr_t` zeros, `Float` zeros do not have
150///   a precision.
151/// - The types of `mpfr_t` components are configuration- and platform-dependent. The types of
152///   `Float` components are platform-independent, although the `Limb` type is
153///   configuration-dependent: it is `u64` by default, but may be changed to `u32` using the
154///   `--32_bit_limbs` compiler flag. The type of the exponent is always `i32` and the type of the
155///   precision is always `u64`. The `Limb` type only has a visible effect on the functions that
156///   extract the raw significand. All other functions have the same interface when compiled with
157///   either `Limb` type.
158///
159/// `Float`s whose precision is 64 bits or less can be represented without any memory allocation.
160/// (Unless Malachite is compiled with `32_bit_limbs`, in which case the limit is 32).
161#[derive(Clone)]
162pub struct Float(pub(crate) InnerFloat);
163
164// We want to limit the visibility of the `NaN`, `Zero`, `Infinity`, and `Finite` constructors to
165// within this crate. To do this, we wrap the `InnerFloat` enum in a struct that gets compiled away.
166#[derive(Clone)]
167pub(crate) enum InnerFloat {
168    NaN,
169    Infinity {
170        sign: bool,
171    },
172    Zero {
173        sign: bool,
174    },
175    Finite {
176        sign: bool,
177        exponent: i32,
178        precision: u64,
179        significand: Natural,
180    },
181}
182
183#[inline]
184pub(crate) fn significand_bits(significand: &Natural) -> u64 {
185    significand.limb_count() << Limb::LOG_WIDTH
186}
187
188impl Float {
189    /// The maximum raw exponent of any [`Float`], equal to $2^{30}-1$, or $1,073,741,823$. This is
190    /// one more than the maximum scientific exponent. If we write a [`Float`] as $\pm m2^e$, with
191    /// $1\leq m<2$ and $e$ an integer, we must have $e\leq 2^{30}-2$. If the result of a
192    /// calculation would produce a [`Float`] with an exponent larger than this, $\pm\infty$ is
193    /// returned instead.
194    pub const MAX_EXPONENT: i32 = 0x3fff_ffff;
195    /// The minimum raw exponent of any [`Float`], equal to $-(2^{30}-1)$, or $-1,073,741,823$. This
196    /// is one more than the minimum scientific exponent. If we write a [`Float`] as $\pm m2^e$,
197    /// with $1\leq m<2$ and $e$ an integer, we must have $e\geq -2^{30}$. If the result of a
198    /// calculation would produce a [`Float`] with an exponent smaller than this, $\pm0.0$ is
199    /// returned instead.
200    pub const MIN_EXPONENT: i32 = -Float::MAX_EXPONENT;
201
202    #[cfg(feature = "test_build")]
203    pub fn is_valid(&self) -> bool {
204        match self {
205            Float(Finite {
206                precision,
207                significand,
208                exponent,
209                ..
210            }) => {
211                if *precision == 0
212                    || !significand.is_valid()
213                    || *exponent > Float::MAX_EXPONENT
214                    || *exponent < Float::MIN_EXPONENT
215                {
216                    return false;
217                }
218                let bits = significand.significant_bits();
219                bits != 0
220                    && bits.divisible_by_power_of_2(Limb::LOG_WIDTH)
221                    && *precision <= bits
222                    && bits - precision < Limb::WIDTH
223                    && significand.divisible_by_power_of_2(bits - precision)
224            }
225            _ => true,
226        }
227    }
228}
229
230/// `ComparableFloat` is a wrapper around a [`Float`], taking the [`Float`] by value.
231///
232/// `CompatableFloat` has different comparison behavior than [`Float`]. See the [`Float`]
233/// documentation for its comparison behavior, which is largely derived from the IEEE 754
234/// specification; the `ComparableFloat` behavior, on the other hand, is more mathematically
235/// well-behaved, and respects the principle that equality should be the finest equivalence
236/// relation: that is, that two equal objects should not be different in any way.
237///
238/// To be more specific: when a [`Float`] is wrapped in a `ComparableFloat`,
239/// - `NaN` is not equal to any other [`Float`], but equal to itself;
240/// - Positive and negative zero are not equal to each other;
241/// - Ordering is total. Negative zero is ordered to be smaller than positive zero, and `NaN` is
242///   arbitrarily ordered to be between the two zeros;
243/// - Two [`Float`]s with different precisions but representing the same value are unequal, and the
244///   one with the greater precision is ordered to be larger;
245/// - The hashing function is compatible with equality.
246///
247/// The analogous wrapper for primitive floats is
248/// [`NiceFloat`](malachite_base::num::float::NiceFloat). However,
249/// [`NiceFloat`](malachite_base::num::float::NiceFloat) also facilitates better string conversion,
250/// something that isn't necessary for [`Float`]s
251///
252/// `ComparableFloat` owns its float. This is useful in many cases, for example if you want to use
253/// [`Float`]s as keys in a hash map. In other situations, it is better to use
254/// [`ComparableFloatRef`], which only has a reference to its float.
255#[derive(Clone)]
256pub struct ComparableFloat(pub Float);
257
258/// `ComparableFloatRef` is a wrapper around a [`Float`], taking the [`Float`] be reference.
259///
260/// See the [`ComparableFloat`] documentation for details.
261#[derive(Clone)]
262pub struct ComparableFloatRef<'a>(pub &'a Float);
263
264impl ComparableFloat {
265    pub const fn as_ref(&self) -> ComparableFloatRef<'_> {
266        ComparableFloatRef(&self.0)
267    }
268}
269
270impl Deref for ComparableFloat {
271    type Target = Float;
272
273    /// Allows a [`ComparableFloat`] to dereference to a [`Float`].
274    ///
275    /// ```
276    /// use malachite_base::num::basic::traits::One;
277    /// use malachite_float::{ComparableFloat, Float};
278    ///
279    /// let x = ComparableFloat(Float::ONE);
280    /// assert_eq!(*x, Float::ONE);
281    /// ```
282    fn deref(&self) -> &Float {
283        &self.0
284    }
285}
286
287impl Deref for ComparableFloatRef<'_> {
288    type Target = Float;
289
290    /// Allows a [`ComparableFloatRef`] to dereference to a [`Float`].
291    ///
292    /// ```
293    /// use malachite_base::num::basic::traits::One;
294    /// use malachite_float::{ComparableFloatRef, Float};
295    ///
296    /// let x = Float::ONE;
297    /// let y = ComparableFloatRef(&x);
298    /// assert_eq!(*y, Float::ONE);
299    /// ```
300    fn deref(&self) -> &Float {
301        self.0
302    }
303}
304
305/// Traits for arithmetic.
306pub mod arithmetic;
307#[macro_use]
308/// Basic traits for working with [`Float`]s.
309pub mod basic;
310/// Traits for comparing [`Float`]s for equality or order.
311pub mod comparison;
312/// Functions that produce [`Float`] approximations of mathematical constants, using a given
313/// precision and rounding mode.
314pub mod constants;
315/// Traits for converting to and from [`Float`]s, including converting [`Float`]s to and from
316/// strings.
317pub mod conversion;
318/// Iterators that generate [`Float`]s without repetition.
319pub mod exhaustive;
320#[cfg(feature = "random")]
321/// Iterators that generate [`Float`]s randomly.
322pub mod random;
323
324#[cfg(feature = "test_build")]
325pub mod test_util;