malachite_q/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 [`Rational`]s. The name of this crate refers to the mathematical symbol for
10//! rational numbers, $$\mathbb{Q}$$.
11//! - There are many functions defined on [`Rational`]s.
12//! These include
13//! - All the ones you'd expect, like addition, subtraction, multiplication, and division;
14//! - Functions related to conversion between [`Rational`]s and other kinds of numbers, including
15//! primitive floats;
16//! - Functions for Diophantine approximation;
17//! - Functions for expressing [`Rational`]s in scientific notation.
18//! - The numerators and denominators of [`Rational`]s are stored as [`Natural`]s, so [`Rational`]s
19//! with small numerators and denominators can be stored entirely on the stack.
20//! - Most arithmetic involving [`Rational`]s requires (automatically) reducing the numerator and
21//! denominator. This is done very efficiently by using the high performance GCD and exact
22//! division algorithms implemented by [`Natural`]s.
23//!
24//! # Demos and benchmarks
25//! This crate comes with a `bin` target that can be used for running demos and benchmarks.
26//! - Almost all of the public functions in this crate have an associated demo. Running a demo
27//! shows you a function's behavior on a large number of inputs. For example, to demo
28//! [`Rational`] addition, you can use the following command:
29//! ```text
30//! cargo run --features bin_build --release -- -l 10000 -m exhaustive -d demo_rational_add
31//! ```
32//! This command uses the `exhaustive` mode, which generates every possible input, generally
33//! starting with the simplest input and progressing to more complex ones. Another mode is
34//! `random`. The `-l` flag specifies how many inputs should be generated.
35//! - You can use a similar command to run benchmarks. The following command benchmarks various
36//! addition algorithms:
37//! ```text
38//! cargo run --features bin_build --release -- -l 1000000 -m random -b \
39//! benchmark_rational_add_algorithms -o add-bench.gp
40//! ```
41//! or addition implementations of other libraries:
42//! ```text
43//! cargo run --features bin_build --release -- -l 1000000 -m random -b \
44//! benchmark_rational_add_assign_library_comparison -o add-bench.gp
45//! ```
46//! This creates a file called gcd-bench.gp. You can use gnuplot to create an SVG from it like
47//! so:
48//! ```text
49//! gnuplot -e "set terminal svg; l \"gcd-bench.gp\"" > gcd-bench.svg
50//! ```
51//!
52//! The list of available demos and benchmarks is not documented anywhere; you must find them by
53//! browsing through
54//! [`bin_util/demo_and_bench`](https://github.com/mhogrefe/malachite/tree/master/malachite-q/src/bin_util/demo_and_bench).
55//!
56//! # Features
57//! - `32_bit_limbs`: Sets the type of [`Limb`](malachite_nz#limbs) to [`u32`] instead of the
58//! default, [`u64`].
59//! - `test_build`: A large proportion of the code in this crate is only used for testing. For a
60//! typical user, building this code would result in an unnecessarily long compilation time and
61//! an unnecessarily large binary. My solution is to only build this code when the `test_build`
62//! feature is enabled. If you want to run unit tests, you must enable `test_build`. However,
63//! doctests don't require it, since they only test the public interface.
64//! - `bin_build`: This feature is used to build the code for demos and benchmarks, which also
65//! takes a long time to build. Enabling this feature also enables `test_build`.
66
67#![allow(
68 unstable_name_collisions,
69 clippy::assertions_on_constants,
70 clippy::cognitive_complexity,
71 clippy::many_single_char_names,
72 clippy::range_plus_one,
73 clippy::suspicious_arithmetic_impl,
74 clippy::suspicious_op_assign_impl,
75 clippy::too_many_arguments,
76 clippy::type_complexity,
77 clippy::upper_case_acronyms
78)]
79#![warn(
80 clippy::cast_lossless,
81 clippy::explicit_into_iter_loop,
82 clippy::explicit_iter_loop,
83 clippy::filter_map_next,
84 clippy::large_digit_groups,
85 clippy::manual_filter_map,
86 clippy::manual_find_map,
87 clippy::map_flatten,
88 clippy::map_unwrap_or,
89 clippy::match_same_arms,
90 clippy::missing_const_for_fn,
91 clippy::mut_mut,
92 clippy::needless_borrow,
93 clippy::needless_continue,
94 clippy::needless_pass_by_value,
95 clippy::print_stdout,
96 clippy::redundant_closure_for_method_calls,
97 clippy::single_match_else,
98 clippy::trait_duplication_in_bounds,
99 clippy::type_repetition_in_bounds,
100 clippy::uninlined_format_args,
101 clippy::unused_self,
102 clippy::if_not_else,
103 clippy::manual_assert,
104 clippy::range_plus_one,
105 clippy::redundant_else,
106 clippy::semicolon_if_nothing_returned,
107 clippy::cloned_instead_of_copied,
108 clippy::flat_map_option,
109 clippy::unnecessary_wraps,
110 clippy::unnested_or_patterns,
111 clippy::trivially_copy_pass_by_ref
112)]
113#![cfg_attr(not(any(feature = "test_build", feature = "random")), no_std)]
114
115extern crate alloc;
116
117#[macro_use]
118extern crate malachite_base;
119extern crate malachite_nz;
120#[cfg(feature = "serde")]
121#[macro_use]
122extern crate serde;
123
124#[cfg(feature = "test_build")]
125extern crate itertools;
126#[cfg(feature = "test_build")]
127extern crate num;
128#[cfg(feature = "test_build")]
129extern crate rug;
130
131use malachite_base::named::Named;
132#[cfg(feature = "test_build")]
133use malachite_base::num::arithmetic::traits::CoprimeWith;
134use malachite_base::num::basic::traits::{NegativeOne, One, OneHalf, Two, Zero};
135use malachite_base::num::logic::traits::SignificantBits;
136use malachite_nz::natural::Natural;
137
138/// A rational number.
139///
140/// `Rational`s whose numerator and denominator have 64 significant bits or fewer can be represented
141/// without any memory allocation. (Unless Malachite is compiled with `32_bit_limbs`, in which case
142/// the limit is 32).
143#[derive(Clone, Hash, Eq, PartialEq)]
144#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
145pub struct Rational {
146 // whether the `Rational` is non-negative
147 #[cfg_attr(feature = "serde", serde(rename = "s"))]
148 pub(crate) sign: bool,
149 #[cfg_attr(feature = "serde", serde(rename = "n"))]
150 pub(crate) numerator: Natural,
151 #[cfg_attr(feature = "serde", serde(rename = "d"))]
152 pub(crate) denominator: Natural,
153}
154
155impl Rational {
156 // Returns true iff `self` is valid.
157 //
158 // To be valid, its denominator must be nonzero, its numerator and denominator must be
159 // relatively prime, and if its numerator is zero, then `sign` must be `true`. All `Rational`s
160 // must be valid.
161 #[cfg(feature = "test_build")]
162 pub fn is_valid(&self) -> bool {
163 self.denominator != 0
164 && (self.sign || self.numerator != 0)
165 && (&self.numerator).coprime_with(&self.denominator)
166 }
167}
168
169impl SignificantBits for &Rational {
170 /// Returns the sum of the bits needed to represent the numerator and denominator.
171 ///
172 /// # Worst-case complexity
173 /// Constant time and additional memory.
174 ///
175 /// # Examples
176 /// ```
177 /// use malachite_base::num::basic::traits::Zero;
178 /// use malachite_base::num::logic::traits::SignificantBits;
179 /// use malachite_q::Rational;
180 /// use std::str::FromStr;
181 ///
182 /// assert_eq!(Rational::ZERO.significant_bits(), 1);
183 /// assert_eq!(
184 /// Rational::from_str("-100/101").unwrap().significant_bits(),
185 /// 14
186 /// );
187 /// ```
188 fn significant_bits(self) -> u64 {
189 self.numerator.significant_bits() + self.denominator.significant_bits()
190 }
191}
192
193/// The constant 0.
194impl Zero for Rational {
195 const ZERO: Rational = Rational {
196 sign: true,
197 numerator: Natural::ZERO,
198 denominator: Natural::ONE,
199 };
200}
201
202/// The constant 1.
203impl One for Rational {
204 const ONE: Rational = Rational {
205 sign: true,
206 numerator: Natural::ONE,
207 denominator: Natural::ONE,
208 };
209}
210
211/// The constant 2.
212impl Two for Rational {
213 const TWO: Rational = Rational {
214 sign: true,
215 numerator: Natural::TWO,
216 denominator: Natural::ONE,
217 };
218}
219
220/// The constant -1.
221impl NegativeOne for Rational {
222 const NEGATIVE_ONE: Rational = Rational {
223 sign: false,
224 numerator: Natural::ONE,
225 denominator: Natural::ONE,
226 };
227}
228
229/// The constant 1/2.
230impl OneHalf for Rational {
231 const ONE_HALF: Rational = Rational {
232 sign: true,
233 numerator: Natural::ONE,
234 denominator: Natural::TWO,
235 };
236}
237
238impl Default for Rational {
239 /// The default value of a [`Rational`], 0.
240 fn default() -> Rational {
241 Rational::ZERO
242 }
243}
244
245// Implements `Named` for `Rational`.
246impl_named!(Rational);
247
248/// Traits for arithmetic.
249pub mod arithmetic;
250/// Traits for comparing [`Rational`]s for equality or order.
251pub mod comparison;
252/// Traits for converting to and from [`Rational`]s, converting to and from strings, and extracting
253/// digits and continued fractions.
254pub mod conversion;
255/// Iterators that generate [`Rational`]s without repetition.
256pub mod exhaustive;
257#[cfg(feature = "random")]
258/// Iterators that generate [`Rational`]s randomly.
259pub mod random;
260
261#[cfg(feature = "test_build")]
262pub mod test_util;