104 lines
2.9 KiB
Swift
104 lines
2.9 KiB
Swift
// FractionTests.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Testing
|
||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||
|
||
@Suite("Fraction — exact rational arithmetic for Score")
|
||
struct FractionTests {
|
||
|
||
@Test func reductionAtConstruction() {
|
||
let f: Fraction = Fraction(num: 6, den: 8)
|
||
#expect(f.num == 3)
|
||
#expect(f.den == 4)
|
||
}
|
||
|
||
@Test func signNormalisation() {
|
||
let f: Fraction = Fraction(num: 3, den: -4)
|
||
#expect(f.num == -3)
|
||
#expect(f.den == 4)
|
||
|
||
let g: Fraction = Fraction(num: -6, den: -8)
|
||
#expect(g.num == 3)
|
||
#expect(g.den == 4)
|
||
}
|
||
|
||
@Test func zeroAndOne() {
|
||
#expect(Fraction.zero.num == 0)
|
||
#expect(Fraction.zero.den == 1)
|
||
#expect(Fraction.one.num == 1)
|
||
#expect(Fraction.one.den == 1)
|
||
}
|
||
|
||
@Test func addition() {
|
||
// 1/2 + 1/3 = 5/6
|
||
let s: Fraction = Fraction(num: 1, den: 2) + Fraction(num: 1, den: 3)
|
||
#expect(s.num == 5)
|
||
#expect(s.den == 6)
|
||
}
|
||
|
||
@Test func additionReducesResult() {
|
||
// 1/4 + 1/4 = 1/2 (not 2/4)
|
||
let s: Fraction = Fraction(num: 1, den: 4) + Fraction(num: 1, den: 4)
|
||
#expect(s.num == 1)
|
||
#expect(s.den == 2)
|
||
}
|
||
|
||
@Test func multiplication() {
|
||
// (2/3) * (3/4) = 1/2 (after cross-cancellation)
|
||
let p: Fraction = Fraction(num: 2, den: 3) * Fraction(num: 3, den: 4)
|
||
#expect(p.num == 1)
|
||
#expect(p.den == 2)
|
||
}
|
||
|
||
@Test func tupletScaleMath() {
|
||
// Triplet inside quintuplet inside the outer measure:
|
||
// outer scale 1/1; quintuplet × 4/5; triplet × 2/3
|
||
let s: Fraction = Fraction.one
|
||
* Fraction(num: 4, den: 5)
|
||
* Fraction(num: 2, den: 3)
|
||
#expect(s.num == 8)
|
||
#expect(s.den == 15)
|
||
}
|
||
|
||
@Test func subtraction() {
|
||
// 1/2 - 1/3 = 1/6
|
||
let d: Fraction = Fraction(num: 1, den: 2) - Fraction(num: 1, den: 3)
|
||
#expect(d.num == 1)
|
||
#expect(d.den == 6)
|
||
}
|
||
|
||
@Test func comparison() {
|
||
let half: Fraction = Fraction(num: 1, den: 2)
|
||
let third: Fraction = Fraction(num: 1, den: 3)
|
||
#expect(third < half)
|
||
#expect(!(half < third))
|
||
#expect(half == Fraction(num: 2, den: 4))
|
||
}
|
||
|
||
@Test func doubleConversion() {
|
||
let f: Fraction = Fraction(num: 1, den: 4)
|
||
#expect(abs(f.double - 0.25) < 1e-15)
|
||
}
|
||
|
||
@Test func gcdEdges() {
|
||
#expect(Fraction.gcd(0, 0) == 0)
|
||
#expect(Fraction.gcd(12, 0) == 12)
|
||
#expect(Fraction.gcd(0, 12) == 12)
|
||
#expect(Fraction.gcd(12, 8) == 4)
|
||
}
|
||
|
||
@Test func exactSumOfThirds() {
|
||
// 1/3 + 1/3 + 1/3 == 1 — the canonical FP failure case must succeed exactly
|
||
var acc: Fraction = Fraction.zero
|
||
for _ in 0..<3 {
|
||
acc += Fraction(num: 1, den: 3)
|
||
}
|
||
#expect(acc.num == 1)
|
||
#expect(acc.den == 1)
|
||
}
|
||
}
|