malachite_q/arithmetic/abs.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
9use crate::Rational;
10use malachite_base::num::arithmetic::traits::{Abs, AbsAssign};
11
12impl Abs for Rational {
13 type Output = Self;
14
15 /// Takes the absolute value of a [`Rational`], taking the [`Rational`] by value.
16 ///
17 /// $$
18 /// f(x) = |x|.
19 /// $$
20 ///
21 /// # Worst-case complexity
22 /// Constant time and additional memory.
23 ///
24 /// # Examples
25 /// ```
26 /// use malachite_base::num::arithmetic::traits::Abs;
27 /// use malachite_base::num::basic::traits::Zero;
28 /// use malachite_q::Rational;
29 ///
30 /// assert_eq!(Rational::ZERO.abs(), 0);
31 /// assert_eq!(Rational::from_signeds(22, 7).abs().to_string(), "22/7");
32 /// assert_eq!(Rational::from_signeds(-22, 7).abs().to_string(), "22/7");
33 /// ```
34 fn abs(mut self) -> Self {
35 self.sign = true;
36 self
37 }
38}
39
40impl Abs for &Rational {
41 type Output = Rational;
42
43 /// Takes the absolute value of a [`Rational`], taking the [`Rational`] by reference.
44 ///
45 /// $$
46 /// f(x) = |x|.
47 /// $$
48 ///
49 /// # Worst-case complexity
50 /// $T(n) = O(n)$
51 ///
52 /// $M(n) = O(n)$
53 ///
54 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
55 ///
56 /// # Examples
57 /// ```
58 /// use malachite_base::num::arithmetic::traits::Abs;
59 /// use malachite_base::num::basic::traits::Zero;
60 /// use malachite_q::Rational;
61 ///
62 /// assert_eq!((&Rational::ZERO).abs(), 0);
63 /// assert_eq!((&Rational::from_signeds(22, 7)).abs().to_string(), "22/7");
64 /// assert_eq!((&Rational::from_signeds(-22, 7)).abs().to_string(), "22/7");
65 /// ```
66 fn abs(self) -> Rational {
67 Rational {
68 sign: true,
69 numerator: self.numerator.clone(),
70 denominator: self.denominator.clone(),
71 }
72 }
73}
74
75impl AbsAssign for Rational {
76 /// Replaces a [`Rational`] with its absolute value.
77 ///
78 /// $$
79 /// x \gets |x|.
80 /// $$
81 ///
82 /// # Examples
83 /// ```
84 /// use malachite_base::num::arithmetic::traits::AbsAssign;
85 /// use malachite_base::num::basic::traits::Zero;
86 /// use malachite_q::Rational;
87 ///
88 /// let mut x = Rational::ZERO;
89 /// x.abs_assign();
90 /// assert_eq!(x, 0);
91 ///
92 /// let mut x = Rational::from_signeds(22, 7);
93 /// x.abs_assign();
94 /// assert_eq!(x.to_string(), "22/7");
95 ///
96 /// let mut x = Rational::from_signeds(-22, 7);
97 /// x.abs_assign();
98 /// assert_eq!(x.to_string(), "22/7");
99 /// ```
100 fn abs_assign(&mut self) {
101 self.sign = true;
102 }
103}