Represents a detached arithmetic fraction with normalization.
This class provides arithmetic operations on rational numbers without attaching them to the JSON DOM. It is intended for musical-duration and proportional calculations where a simple fraction is needed independently of the MNX DOM structure.
A FractionValue constructed from a numerator and denominator preserves the values exactly as provided. Arithmetic operations (+=, -=, *=, /=) reduce the result to lowest terms using std::gcd. Call reduce() explicitly if you need a reduced form immediately after construction.
The class supports:
- Exact rational arithmetic (addition, subtraction, multiplication, division)
- Normalization to lowest terms after each operation
- Comparison operators (in helper section)
Compound assignment operators (+=, -=, *=, /=) are implemented as members. Binary operators (+, -, *, /) are implemented as non-member functions to allow symmetric conversions and correct C++ arithmetic semantics.
| constexpr bool mnx::FractionValue::expressWithDenominator |
( |
NumType |
targetDenominator | ) |
|
|
inlineconstexpr |
Attempts to express this fraction with the given denominator.
If the current value can be written exactly with targetDenominator using an integer numerator, the numerator and denominator are updated to use that denominator and the function returns true. Otherwise, the fraction is left unchanged and the function returns false.
This function does not require the fraction to be in reduced form. It computes a reduced logical form internally when determining whether the requested denominator is compatible.
Examples:
- 1/1 expressed with denominator 4 becomes 4/4 and returns true.
- 3/2 expressed with denominator 4 becomes 6/4 and returns true.
- 2/6 (i.e. 1/3) expressed with denominator 3 becomes 1/3 and returns true.
- 1/3 expressed with denominator 4 cannot be represented exactly with an integer numerator, so the call returns false and the fraction remains 1/3.
A zero fraction (0 / d) can always be expressed with any nonzero targetDenominator; in that case the result becomes 0 / targetDenominator.
- Parameters
-
| targetDenominator | The desired denominator. If zero, the call fails and the fraction is left unchanged. |
- Returns
- true if the fraction was successfully rewritten with the given denominator; false if no exact integer representation exists or if
targetDenominator is zero.