MUSX Document Model
Loading...
Searching...
No Matches
Fraction.h
1/*
2 * Copyright (C) 2025, Robert Patterson
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22#pragma once
23
24#include <iostream>
25#include <numeric>
26#include <stdexcept>
27#include <limits>
28
29#include "musx/dom/Fundamentals.h"
30
31namespace musx {
32namespace util {
33
38class [[nodiscard]] Fraction {
39private:
40 int m_numerator = 0;
41 int m_denominator = 1;
42
47 static constexpr std::pair<int, int> reduce(int num, int den) {
48 int gcd = std::gcd(num, den);
49 num /= gcd;
50 den /= gcd;
51
52 // Ensure denominator is always positive
53 if (den < 0) {
54 num = -num;
55 den = -den;
56 }
57
58 return {num, den};
59 }
60
61 constexpr static Fraction fromConstExpr(int num, int den)
62 {
63 auto [n, d] = reduce(num, den);
64 auto result = Fraction(n);
65 result.m_denominator = d;
66 return result;
67 }
68
69 friend class std::numeric_limits<Fraction>;
70
71public:
72 constexpr Fraction() = default;
73
81 Fraction(int num, int den)
82 {
83 if (den == 0) {
84 throw std::invalid_argument("Denominator cannot be zero.");
85 }
86
87 auto [n, d] = reduce(num, den);
88 m_numerator = n;
89 m_denominator = d;
90 }
91
97 constexpr Fraction(int value) : m_numerator(value), m_denominator(1) {}
98
103 static constexpr Fraction fromEdu(dom::Edu edu) { return fromConstExpr(edu, EDU_PER_WHOLE_NOTE); }
104
107 static constexpr Fraction fromPercent(int percent) { return fromConstExpr(percent, 100); }
108
113 constexpr int numerator() const { return m_numerator; }
114
119 constexpr int denominator() const { return m_denominator; }
120
125 constexpr int quotient() const {
126 return m_numerator / m_denominator;
127 }
128
133 Fraction constexpr remainder() const {
134 return fromConstExpr(m_numerator % m_denominator, m_denominator);
135 }
136
140 return Fraction(m_denominator, m_numerator);
141 }
142
149 constexpr dom::Edu calcEduDuration() const
150 {
151 using Edu = dom::Edu;
152 using Wide = std::int64_t;
153
154 // Do the scaling in wide integer to avoid overflow.
155 const auto num = Wide(m_numerator) * Wide(EDU_PER_WHOLE_NOTE);
156 const auto den = Wide(m_denominator); // always > 0 by class invariant
157
158 // Round to nearest, 0.5 away from zero, without using double.
159 auto rounded = Wide{};
160 if (num >= 0) {
161 rounded = (num + den / 2) / den;
162 } else {
163 rounded = (num - den / 2) / den;
164 }
165
166 // Saturate to dom::Edu range.
167 constexpr auto maxEdu = static_cast<Wide>((std::numeric_limits<Edu>::max)());
168 constexpr auto minEdu = static_cast<Wide>((std::numeric_limits<Edu>::min)());
169
170 if (rounded > maxEdu) {
171 rounded = maxEdu;
172 } else if (rounded < minEdu) {
173 rounded = minEdu;
174 }
175
176 return Edu(static_cast<int>(rounded));
177 }
178
182 constexpr Fraction abs() const
183 {
184 if (numerator() < 0)
185 return fromConstExpr(-numerator(), denominator());
186 return *this;
187 }
188
192 constexpr double toDouble() const {
193 return double(m_numerator) / double(m_denominator);
194 }
195
201 Fraction constexpr operator+(const Fraction& other) const {
202 return fromConstExpr(
203 m_numerator * other.m_denominator + other.m_numerator * m_denominator,
204 m_denominator * other.m_denominator
205 );
206 }
207
213 Fraction constexpr operator-(const Fraction& other) const {
214 return fromConstExpr(
215 m_numerator * other.m_denominator - other.m_numerator * m_denominator,
216 m_denominator * other.m_denominator
217 );
218 }
219
225 Fraction constexpr operator*(const Fraction& other) const {
226 return fromConstExpr(
227 m_numerator * other.m_numerator,
228 m_denominator * other.m_denominator
229 );
230 }
231
239 Fraction operator/(const Fraction& other) const {
240 return Fraction(
241 m_numerator * other.m_denominator,
242 m_denominator * other.m_numerator
243 );
244 }
245
251 constexpr Fraction& operator+=(const Fraction& other) {
252 *this = *this + other;
253 return *this;
254 }
255
261 constexpr Fraction& operator-=(const Fraction& other) {
262 *this = *this - other;
263 return *this;
264 }
265
271 constexpr Fraction& operator*=(const Fraction& other) {
272 *this = *this * other;
273 return *this;
274 }
275
282 Fraction& operator/=(const Fraction& other) {
283 *this = *this / other;
284 return *this;
285 }
286
292 constexpr bool operator==(const Fraction& other) const {
293 return m_numerator == other.m_numerator && m_denominator == other.m_denominator;
294 }
295
301 constexpr bool operator!=(const Fraction& other) const {
302 return !(*this == other);
303 }
304
310 constexpr bool operator<(const Fraction& other) const {
311 double lhs = static_cast<double>(m_numerator) / m_denominator;
312 double rhs = static_cast<double>(other.m_numerator) / other.m_denominator;
313 return lhs < rhs;
314 }
315
321 constexpr bool operator<=(const Fraction& other) const {
322 return *this < other || *this == other;
323 }
324
330 constexpr bool operator>(const Fraction& other) const {
331 return !(*this <= other);
332 }
333
339 constexpr bool operator>=(const Fraction& other) const {
340 return !(*this < other);
341 }
342
347 constexpr explicit operator bool() const noexcept {
348 return m_numerator != 0;
349 }
350
357 friend std::ostream& operator<<(std::ostream& os, const Fraction& frac) {
358 os << frac.m_numerator;
359 if (frac.m_denominator != 1) {
360 os << "/" << frac.m_denominator;
361 }
362 return os;
363 }
364
372 friend std::istream& operator>>(std::istream& is, Fraction& frac) {
373 int num, den;
374 char sep;
375 is >> num >> sep >> den;
376 if (sep != '/' || den == 0) {
377 throw std::invalid_argument("Invalid fraction format or zero m_denominator.");
378 }
379 frac = Fraction(num, den);
380 return is;
381 }
382};
383
385constexpr Fraction abs(const Fraction& v) noexcept
386{
387 return v.abs();
388}
389
390} // namespace util
391} // namespace musx
392
393#ifndef DOXYGEN_SHOULD_IGNORE_THIS
394#include <limits>
395
396namespace std {
397template <>
398class numeric_limits<musx::util::Fraction> {
399public:
400 static constexpr bool is_specialized = true;
401
402 // Smallest positive normalized value (not necessarily lowest)
403 static constexpr musx::util::Fraction min() noexcept {
404 return musx::util::Fraction::fromConstExpr(1, std::numeric_limits<int>::max());
405 }
406
407 // Largest representable positive fraction
408 static constexpr musx::util::Fraction max() noexcept {
409 return musx::util::Fraction(std::numeric_limits<int>::max());
410 }
411
412 // Most negative representable fraction
413 static constexpr musx::util::Fraction lowest() noexcept {
414 return musx::util::Fraction(std::numeric_limits<int>::lowest());
415 }
416
417 static constexpr int digits = std::numeric_limits<int>::digits;
418 static constexpr int digits10 = std::numeric_limits<int>::digits10;
419
420 static constexpr bool is_signed = true;
421 static constexpr bool is_integer = false;
422 static constexpr bool is_exact = true;
423 static constexpr bool has_infinity = false;
424 static constexpr bool has_quiet_NaN = false;
425 static constexpr bool has_signaling_NaN = false;
426
427 static constexpr musx::util::Fraction epsilon() noexcept {
428 return musx::util::Fraction::fromConstExpr(1, std::numeric_limits<int>::max());
429 }
430
431 static constexpr musx::util::Fraction round_error() noexcept {
432 return musx::util::Fraction(0);
433 }
434
435 static constexpr int radix = 2;
436
437 static constexpr musx::util::Fraction infinity() noexcept { return musx::util::Fraction(0); }
438 static musx::util::Fraction quiet_NaN() noexcept { return musx::util::Fraction(0); }
439 static musx::util::Fraction signaling_NaN() noexcept { return musx::util::Fraction(0); }
440
441 static constexpr bool is_iec559 = false;
442 static constexpr bool is_bounded = true;
443 static constexpr bool is_modulo = false;
444 static constexpr bool traps = true; // Because invalid construction throws
445 static constexpr bool tinyness_before = false;
446 static constexpr float_round_style round_style = round_indeterminate;
447};
448
449template <>
450struct hash<musx::util::Fraction>
451{
452 size_t operator()(const musx::util::Fraction& frac) const noexcept
453 {
454 // boost algorithm tailored to Fraction
455 size_t seed = std::hash<int>{}(frac.numerator());
456 seed ^= std::hash<int>{}(frac.denominator()) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
457 return seed;
458 }
459};
460
461} // namespace std
462#endif // DOXYGEN_SHOULD_IGNORE_THIS
463
A class to represent fractions with integer m_numerator and m_denominator, automatically reduced to s...
Definition Fraction.h:38
constexpr int quotient() const
Returns the integer (whole number) part of the fraction.
Definition Fraction.h:125
constexpr double toDouble() const
Converts the fraction to floating point double.
Definition Fraction.h:192
constexpr int numerator() const
Gets the m_numerator of the fraction.
Definition Fraction.h:113
static constexpr Fraction fromPercent(int percent)
Constructs a Fraction from a percent (where 100 is 100%)
Definition Fraction.h:107
Fraction constexpr operator*(const Fraction &other) const
Multiplies two fractions.
Definition Fraction.h:225
constexpr Fraction & operator-=(const Fraction &other)
Compound subtraction assignment operator.
Definition Fraction.h:261
constexpr bool operator<(const Fraction &other) const
Less-than comparison operator.
Definition Fraction.h:310
constexpr int denominator() const
Gets the m_denominator of the fraction.
Definition Fraction.h:119
Fraction reciprocal() const
Returns the reciprocal fraction.
Definition Fraction.h:139
Fraction(int num, int den)
Constructs a Fraction object.
Definition Fraction.h:81
constexpr bool operator<=(const Fraction &other) const
Less-than-or-equal-to comparison operator.
Definition Fraction.h:321
static constexpr Fraction fromEdu(dom::Edu edu)
Constructs a Fraction from edu.
Definition Fraction.h:103
Fraction constexpr operator+(const Fraction &other) const
Adds two fractions.
Definition Fraction.h:201
constexpr dom::Edu calcEduDuration() const
Calculates duration as a fraction of a whole note. The result is rounded to the nearest integer Edu v...
Definition Fraction.h:149
constexpr Fraction abs() const
Calculates the absolute value of a Fraction.
Definition Fraction.h:182
friend std::ostream & operator<<(std::ostream &os, const Fraction &frac)
Stream output operator.
Definition Fraction.h:357
Fraction constexpr remainder() const
Returns the fractional part of the fraction.
Definition Fraction.h:133
friend std::istream & operator>>(std::istream &is, Fraction &frac)
Stream input operator.
Definition Fraction.h:372
constexpr Fraction(int value)
Constructs a Fraction object from an integer.
Definition Fraction.h:97
constexpr bool operator>(const Fraction &other) const
Greater-than comparison operator.
Definition Fraction.h:330
constexpr Fraction & operator*=(const Fraction &other)
Compound multiplication assignment operator.
Definition Fraction.h:271
Fraction constexpr operator-(const Fraction &other) const
Subtracts one fraction from another.
Definition Fraction.h:213
constexpr Fraction & operator+=(const Fraction &other)
Compound addition assignment operator.
Definition Fraction.h:251
constexpr bool operator!=(const Fraction &other) const
Inequality comparison operator.
Definition Fraction.h:301
Fraction operator/(const Fraction &other) const
Divides one fraction by another.
Definition Fraction.h:239
Fraction & operator/=(const Fraction &other)
Compound division assignment operator.
Definition Fraction.h:282
constexpr bool operator==(const Fraction &other) const
Equality comparison operator. (This depends on the fact that instances of Fraction are always reduced...
Definition Fraction.h:292
constexpr bool operator>=(const Fraction &other) const
Greater-than-or-equal-to comparison operator.
Definition Fraction.h:339
int32_t Edu
"Enigma Durational Units" value (1024 per quarter note)
Definition Fundamentals.h:61
object model for musx file (enigmaxml)
Definition BaseClasses.h:36