SPB Git

Repository Public MIT

ExactnessTests.swift 23.3 KB 437 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Calc9// File             : Packages/ORIXUnits/Tests/ORIXUnitsTests/ExactnessTests.swift10// Description      : Exact results, round trips, temperature fixed points,11//                    fuel-economy reciprocity, data prefixes, Double path.12// Module           : ORIXUnitsTests13// Repository       : https://git.spboucher.ai/orix-calc14// Created          : 2026-11-2015// Last Modified    : 2026-11-2016//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : Proprietary, all rights reserved (see license file)82// License File     : LICENSE83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing9293@testable import ORIXUnits9495@Suite("Exactness")96struct ExactnessTests {97    @Test("Defining constants equal their published exact values")98    func definingConstants() {99        #expect(Defining.poundForce.isEquivalent(to: ExactRational("4.4482216152605")))100        #expect(Defining.usGallon.isEquivalent(to: ExactRational("0.003785411784")))101        #expect(Defining.btuIT.isEquivalent(to: ExactRational("1055.05585262")))102        #expect(Defining.mmHg.isEquivalent(to: ExactRational("133.322387415")))103        #expect((Defining.speedOfLight * Defining.julianYear).isEquivalent(to: ExactRational("9460730472580800")))104        #expect(Defining.elementaryCharge.decimalValue == dec("0.0000000000000000001602176634"))105        #expect((Defining.frenchFoot * 180).isEquivalent(to: ExactRational("58.471308")))106        #expect(Defining.pi.doubleValue == Double.pi)107        #expect(Defining.gregorianYear.isEquivalent(to: Defining.day * ExactRational("365.2425")))108    }109110    @Test("Exact decimal results")111    func exactResults() throws {112        #expect(try convert("1", "length.mi", "length.km") == dec("1.609344"))113        #expect(try convert("12", "length.in", "length.ft") == 1)114        #expect(try convert("1", "length.in", "length.m") == dec("0.0254"))115        #expect(try convert("1", "mass.lb", "mass.kg") == dec("0.45359237"))116        #expect(try convert("1", "volume.gal_us", "volume.in3") == 231)117        #expect(try convert("1", "volume.gal_us", "volume.L") == dec("3.785411784"))118        #expect(try convert("1", "volume.gal_imp", "volume.L") == dec("4.54609"))119        #expect(try convert("1", "energy.cal", "energy.J") == dec("4.184"))120        #expect(try convert("1", "pressure.atm", "pressure.Pa") == 101325)121        #expect(try convert("1", "energy.BTU", "energy.J") == dec("1055.05585262"))122        #expect(try convert("1", "length.nmi", "length.m") == 1852)123        #expect(try convert("1", "length.ly", "length.m") == dec("9460730472580800"))124        #expect(try convert("1", "length.au", "length.km") == dec("149597870.7"))125        #expect(try convert("1", "energy.eV", "energy.J") == dec("0.0000000000000000001602176634"))126        #expect(try convert("1", "power.hp", "power.W") == dec("745.69987158227022"))127        #expect(try convert("1", "force.lbf", "force.N") == dec("4.4482216152605"))128        #expect(try convert("1", "pressure.atm", "pressure.Torr") == 760)129        #expect(try convert("1", "area.acre", "area.m2") == dec("4046.8564224"))130        #expect(try convert("3", "length.ft", "length.yd") == 1)131        #expect(try convert("36", "speed.km_h", "speed.m_s") == 10)132        #expect(try convert("0.1", "length.m", "length.cm") == 10)133    }134135    @Test("Round trips a → b → a over every pair of exact linear units")136    func roundTrips() throws {137        let values = ["1", "7", "0.1", "123.456", "-2.5", "1000000"].map(dec)138        var exactPairs = 0139        var roundedPairs = 0140        for category in catalog.categories {141            let units = category.units.filter { $0.precision == .exact && $0.transform.isLinear }142            for a in units {143                for b in units where a.id != b.id {144                    for x in values {145                        let y = try UnitConverter.convert(x, from: a, to: b)146                        let z = try UnitConverter.convert(y, from: b, to: a)147                        if significantDigits(y) <= 30 {148                            // The forward result terminated: the way back must be exact.149                            exactPairs += 1150                            #expect(z == x, "\(x) \(a.id) → \(b.id) → back gave \(z) (via \(y))")151                        } else {152                            roundedPairs += 1153                            #expect(154                                isClose(z, x, relative: dec("1e-36")),155                                "\(x) \(a.id) → \(b.id) → back gave \(z) (via \(y))")156                        }157                    }158                }159            }160        }161        #expect(exactPairs > 10_000)162        #expect(roundedPairs > 1_000)163    }164165    @Test("Round trips through irrational and approximate units stay within 1e-35")166    func roundTripsInexactUnits() throws {167        for unit in catalog.allUnits where unit.precision != .exact {168            let category = try #require(catalog.category(of: unit))169            for other in category.units where other.id != unit.id {170                let y = try UnitConverter.convert(dec("3.25"), from: unit, to: other)171                let z = try UnitConverter.convert(y, from: other, to: unit)172                #expect(isClose(z, dec("3.25"), relative: dec("1e-35")), "\(unit.id) ↔ \(other.id): \(z)")173            }174        }175    }176177    @Test("Identity conversion returns the value unchanged")178    func identity() throws {179        for unit in catalog.allUnits {180            #expect(try UnitConverter.convert(dec("12.5"), from: unit, to: unit) == dec("12.5"))181            #expect(try UnitConverter.convert(12.5, from: unit, to: unit) == 12.5)182        }183    }184185    @Test("Conversion reports whether the decimal is exact")186    func conversionFlags() throws {187        let exact = try UnitConverter.conversion(dec("1"), from: try unit("length.mi"), to: try unit("length.km"))188        #expect(exact == Conversion(value: dec("1.609344"), unitPrecision: .exact, isExactDecimal: true))189        let rounded = try UnitConverter.conversion(dec("1"), from: try unit("length.m"), to: try unit("length.ft"))190        #expect(rounded.value == dec("3.2808398950131233595800524934383202100"))191        #expect(rounded.unitPrecision == .exact && !rounded.isExactDecimal)192        let irrational = try UnitConverter.conversion(dec("180"), from: try unit("angle.deg"), to: try unit("angle.rad"))193        #expect(irrational.unitPrecision == .irrational && !irrational.isExactDecimal)194        #expect(isClose(irrational.value, dec("3.1415926535897932384626433832795028842"), relative: dec("1e-37")))195        let approximate = try UnitConverter.conversion(dec("1"), from: try unit("speed.mach"), to: try unit("speed.m_s"))196        #expect(approximate == Conversion(value: dec("340.294"), unitPrecision: .approximate, isExactDecimal: false))197        let temperature = try UnitConverter.conversion(dec("98.6"), from: try unit("temperature.degF"), to: try unit("temperature.degC"))198        #expect(temperature == Conversion(value: 37, unitPrecision: .exact, isExactDecimal: true))199        let same = try UnitConverter.conversion(dec("2"), from: try unit("length.pc"), to: try unit("length.pc"))200        #expect(same == Conversion(value: 2, unitPrecision: .exact, isExactDecimal: true))201    }202203    @Test("Double strings are read exactly by Decimal")204    func doubleStrings() throws {205        // The Double path relies on these spellings of `Double.description`.206        for (value, text) in [(1e-5, "0.00001"), (2.5e20, "250000000000000000000"), (1e-7, "0.0000001"), (123.456, "123.456"), (5e-324, "")] {207            let parsed = Decimal(string: "\(value)", locale: Locale(identifier: "en_US_POSIX"))208            if text.isEmpty { continue }209            #expect(parsed == dec(text), "\(value)")210        }211    }212213    @Test("Ratios through irrational units do not trap")214    func irrationalRatios() throws {215        let ratio = try #require(try UnitConverter.ratio(from: try unit("length.ly"), to: try unit("length.pc")))216        #expect(isClose(ratio.decimalValue, dec("0.3066013937855505673534506748241696450"), relative: dec("1e-35")))217        for category in catalog.categories {218            for a in category.units {219                for b in category.units {220                    _ = try UnitConverter.ratio(from: a, to: b)221                }222            }223        }224    }225226    @Test("Exact ratio between linear units")227    func ratios() throws {228        let ratio = try #require(try UnitConverter.ratio(from: try unit("length.mi"), to: try unit("length.km")))229        #expect(ratio.decimalValue == dec("1.609344"))230        let inverse = try #require(try UnitConverter.ratio(from: try unit("length.km"), to: try unit("length.mi")))231        #expect((ratio * inverse).isEquivalent(to: .one))232        #expect(ratio.isEquivalent(to: ExactRational("1.609344")))233        #expect(try UnitConverter.ratio(from: try unit("temperature.degC"), to: try unit("temperature.K")) == nil)234        #expect(try UnitConverter.ratio(from: try unit("fuelEconomy.L_100km"), to: try unit("fuelEconomy.km_L")) == nil)235        #expect(throws: UnitError.incompatible(from: "length.m", to: "mass.kg")) {236            try UnitConverter.ratio(from: try unit("length.m"), to: try unit("mass.kg"))237        }238    }239}240241@Suite("Temperature")242struct TemperatureTests {243    @Test("Fixed points")244    func fixedPoints() throws {245        #expect(try convert("-40", "temperature.degC", "temperature.degF") == -40)246        #expect(try convert("-40", "temperature.degF", "temperature.degC") == -40)247        #expect(try convert("0", "temperature.degC", "temperature.degF") == 32)248        #expect(try convert("0", "temperature.degC", "temperature.K") == dec("273.15"))249        #expect(try convert("32", "temperature.degF", "temperature.K") == dec("273.15"))250        #expect(try convert("273.15", "temperature.K", "temperature.degF") == 32)251        #expect(try convert("100", "temperature.degC", "temperature.degF") == 212)252        #expect(try convert("212", "temperature.degF", "temperature.degC") == 100)253        #expect(try convert("98.6", "temperature.degF", "temperature.degC") == 37)254        #expect(try convert("0.01", "temperature.degC", "temperature.K") == dec("273.16"))255    }256257    @Test("Absolute zero")258    func absoluteZero() throws {259        #expect(try convert("0", "temperature.K", "temperature.degC") == dec("-273.15"))260        #expect(try convert("0", "temperature.K", "temperature.degF") == dec("-459.67"))261        #expect(try convert("0", "temperature.K", "temperature.degR") == 0)262        #expect(try convert("-273.15", "temperature.degC", "temperature.K") == 0)263        #expect(try convert("-459.67", "temperature.degF", "temperature.K") == 0)264        #expect(try convert("-459.67", "temperature.degF", "temperature.degC") == dec("-273.15"))265        #expect(try convert("0", "temperature.degR", "temperature.degF") == dec("-459.67"))266        #expect(try convert("491.67", "temperature.degR", "temperature.degC") == 0)267    }268269    @Test("Round trips between all scales are exact for terminating values")270    func roundTrips() throws {271        let ids = ["temperature.K", "temperature.degC", "temperature.degF", "temperature.degR"]272        for a in ids {273            for b in ids {274                for value in ["-40", "0", "25", "451", "1234.5"] {275                    let y = try convert(value, a, b)276                    let z = try UnitConverter.convert(y, from: try unit(b), to: try unit(a))277                    if significantDigits(y) <= 30 {278                        #expect(z == dec(value), "\(value) \(a) → \(b) → \(z)")279                    } else {280                        #expect(isClose(z, dec(value), relative: dec("1e-34")), "\(value) \(a) → \(b) → \(z)")281                    }282                }283            }284        }285    }286287    @Test("Temperature differences ignore the offsets")288    func intervals() throws {289        #expect(try convert("10", "temperature.degC", "temperature.degF", mode: .interval) == 18)290        #expect(try convert("18", "temperature.degF", "temperature.degC", mode: .interval) == 10)291        #expect(try convert("10", "temperature.degC", "temperature.K", mode: .interval) == 10)292        #expect(try convert("9", "temperature.degR", "temperature.K", mode: .interval) == 5)293        #expect(try convert("1", "temperature.K", "temperature.degF", mode: .interval) == dec("1.8"))294        #expect(try convert("0", "temperature.degC", "temperature.degF", mode: .interval) == 0)295        // The absolute reading differs.296        #expect(try convert("10", "temperature.degC", "temperature.degF") == 50)297        // Interval mode is the ordinary conversion for linear units and is refused for reciprocal ones.298        #expect(try convert("1", "length.mi", "length.km", mode: .interval) == dec("1.609344"))299        #expect(throws: UnitError.intervalNotSupported(unit: "fuelEconomy.L_100km")) {300            try convert("1", "fuelEconomy.L_100km", "fuelEconomy.km_L", mode: .interval)301        }302        #expect(throws: UnitError.intervalNotSupported(unit: "fuelEconomy.L_100km")) {303            try convert("1", "fuelEconomy.km_L", "fuelEconomy.L_100km", mode: .interval)304        }305        #expect(try catalog.convert(10.0, from: "°C", to: "°F", mode: .interval) == 18.0)306    }307}308309@Suite("Fuel economy")310struct FuelEconomyTests {311    @Test("L/100 km and km/L are reciprocal")312    func reciprocity() throws {313        #expect(try convert("5", "fuelEconomy.L_100km", "fuelEconomy.km_L") == 20)314        #expect(try convert("20", "fuelEconomy.km_L", "fuelEconomy.L_100km") == 5)315        #expect(try convert("12.5", "fuelEconomy.km_L", "fuelEconomy.L_100km") == 8)316        for value in ["3.9", "5", "7.2", "10", "15.5", "100"] {317            let mpg = try convert(value, "fuelEconomy.L_100km", "fuelEconomy.mpg_us")318            let back = try UnitConverter.convert(mpg, from: try unit("fuelEconomy.mpg_us"), to: try unit("fuelEconomy.L_100km"))319            #expect(isClose(back, dec(value), relative: dec("1e-35")), "\(value) → \(mpg) → \(back)")320            // x L/100 km × y mpg is the constant 100 × (mi/km) / (gal/L).321            let product = dec(value) * mpg322            #expect(isClose(product, dec("235.2145833333333333333333333333333"), relative: dec("1e-31")))323        }324    }325326    @Test("Known values")327    func knownValues() throws {328        // 100 × gal / mi / 8 for each gallon, to 38 digits (computed with Python fractions).329        let us = try convert("8", "fuelEconomy.L_100km", "fuelEconomy.mpg_us")330        #expect(us == dec("29.401822916666666666666666666666666667"))331        let imperial = try convert("8", "fuelEconomy.L_100km", "fuelEconomy.mpg_imp")332        #expect(imperial == dec("35.310117041477769824226517139902966675"))333        // Imperial gallon is larger: the same car shows more mpg (imp) than mpg (US).334        #expect(imperial > us)335        let ratio = try convert("1", "fuelEconomy.mpg_us", "fuelEconomy.mpg_imp")336        #expect(ratio == dec("1.2009499255048549296744092346281975858"))337        #expect(try convert("25", "fuelEconomy.mpg_us", "fuelEconomy.gal_100mi_us") == 4)338        #expect(try convert("4", "fuelEconomy.gal_100mi_us", "fuelEconomy.mpg_us") == 25)339    }340341    @Test("Zero is a typed error on both sides of a reciprocal conversion")342    func zero() throws {343        #expect(throws: UnitError.undefinedAtZero(unit: "fuelEconomy.L_100km")) {344            try convert("0", "fuelEconomy.L_100km", "fuelEconomy.mpg_us")345        }346        #expect(throws: UnitError.undefinedAtZero(unit: "fuelEconomy.L_100km")) {347            try convert("0", "fuelEconomy.mpg_us", "fuelEconomy.L_100km")348        }349        #expect(throws: UnitError.undefinedAtZero(unit: "fuelEconomy.L_100km")) {350            try convert("0", "fuelEconomy.L_100km", "fuelEconomy.L_100km")351        }352        #expect(throws: UnitError.undefinedAtZero(unit: "fuelEconomy.L_100km")) {353            try UnitConverter.convert(0.0, from: try unit("fuelEconomy.km_L"), to: try unit("fuelEconomy.L_100km"))354        }355        #expect(throws: UnitError.undefinedAtZero(unit: "fuelEconomy.gal_100mi_us")) {356            try UnitConverter.binaryConvert(357                0, from: try unit("fuelEconomy.gal_100mi_us"), to: try unit("fuelEconomy.km_L"), mode: .absolute)358        }359        // Zero is fine between two distance-per-volume units.360        #expect(try convert("0", "fuelEconomy.km_L", "fuelEconomy.mpg_us") == 0)361    }362}363364@Suite("Data prefixes")365struct DataPrefixTests {366    @Test("Decimal (SI) versus binary (IEC 80000-13)")367    func decimalVersusBinary() throws {368        #expect(try convert("1", "dataStorage.kB", "dataStorage.B") == 1000)369        #expect(try convert("1", "dataStorage.KiB", "dataStorage.B") == 1024)370        #expect(try convert("1", "dataStorage.MiB", "dataStorage.B") == 1_048_576)371        #expect(try convert("1", "dataStorage.GiB", "dataStorage.B") == 1_073_741_824)372        #expect(try convert("1", "dataStorage.GiB", "dataStorage.GB") == dec("1.073741824"))373        #expect(try convert("1", "dataStorage.TiB", "dataStorage.B") == dec("1099511627776"))374        #expect(try convert("1", "dataStorage.YiB", "dataStorage.B") == dec("1208925819614629174706176"))375        #expect(try convert("1", "dataStorage.YB", "dataStorage.B") == dec("1000000000000000000000000"))376        #expect(try convert("1", "dataStorage.B", "dataStorage.bit") == 8)377        #expect(try convert("1", "dataStorage.B", "dataStorage.nibble") == 2)378        #expect(try convert("1", "dataStorage.MB", "dataStorage.Mbit") == 8)379        #expect(try convert("1024", "dataStorage.MiB", "dataStorage.GiB") == 1)380        #expect(try convert("1000", "dataStorage.MB", "dataStorage.GB") == 1)381        // A "500 GB" drive shown in GiB.382        let shown = try convert("500", "dataStorage.GB", "dataStorage.GiB")383        #expect(isClose(shown, dec("465.66128730773925781250"), relative: dec("1e-22")))384        #expect(try unit("dataStorage.KiB").source == .iec)385        #expect(try unit("dataStorage.kB").source == .si)386    }387388    @Test("Transfer rates")389    func rates() throws {390        #expect(try convert("100", "dataRate.Mbit_s", "dataRate.MB_s") == dec("12.5"))391        #expect(try convert("1", "dataRate.MiB_s", "dataRate.bit_s") == 8_388_608)392        #expect(try convert("1", "dataRate.Gbit_s", "dataRate.MB_s") == 125)393        #expect(try convert("1", "dataRate.GiB_s", "dataRate.MiB_s") == 1024)394    }395}396397@Suite("Double path")398struct DoublePathTests {399    @Test("Decimal-faithful results")400    func faithful() throws {401        #expect(try catalog.convert(12.0, from: "in", to: "ft") == 1.0)402        #expect(try catalog.convert(1.0, from: "mi", to: "km") == 1.609344)403        #expect(try catalog.convert(0.1, from: "m", to: "cm") == 10.0)404        #expect(try catalog.convert(0.3, from: "m", to: "mm") == 300.0)405        #expect(try catalog.convert(98.6, from: "°F", to: "°C") == 37.0)406        #expect(try catalog.convert(-40.0, from: "°C", to: "°F") == -40.0)407        #expect(try catalog.convert(5.0, from: "L/100 km", to: "km/L") == 20.0)408        #expect(try catalog.convert(1e-5, from: "m", to: "µm") == 10.0)409        #expect(try catalog.convert(2.5e20, from: "m", to: "km") == 2.5e17)410        #expect(try catalog.convert(0.0, from: "kg", to: "lb") == 0.0)411        #expect(try catalog.convert(-1.5, from: "km", to: "m") == -1500.0)412    }413414    @Test("Extreme magnitudes, infinities and NaN use binary arithmetic")415    func extremes() throws {416        #expect(try catalog.convert(1e306, from: "km", to: "m") == .infinity)417        #expect(isClose(try catalog.convert(1e200, from: "km", to: "m"), 1e203, relative: 1e-15))418        #expect(isClose(try catalog.convert(1e-200, from: "m", to: "km"), 1e-203, relative: 1e-15))419        #expect(isClose(try catalog.convert(1e-70, from: "eV", to: "J"), 1.602176634e-89, relative: 1e-15))420        #expect(try catalog.convert(Double.infinity, from: "m", to: "ft") == .infinity)421        #expect(try catalog.convert(Double.nan, from: "m", to: "ft").isNaN)422        #expect(isClose(try catalog.convert(1e100, from: "°C", to: "K"), 1e100, relative: 1e-15))423        #expect(throws: UnitError.notRepresentable) {424            try UnitConverter.convert(Decimal.nan, from: try unit("length.m"), to: try unit("length.ft"))425        }426    }427428    @Test("Decimal to Double is correctly rounded")429    func rounding() {430        #expect(dec("0.1").correctlyRoundedDouble == 0.1)431        #expect(dec("1.609344").correctlyRoundedDouble == 1.609344)432        #expect(dec("3.1415926535897932384626433832795028842").correctlyRoundedDouble == Double.pi)433        #expect(Decimal.nan.correctlyRoundedDouble.isNaN)434        #expect(ExactRational("1", over: "3").doubleValue == 1.0 / 3.0)435    }436}437
Files main
Menu

Theme