Tests/OrgCoreTests/CalcNumericTests.swift

168 lines · 11142 bytes

11 symbols in this file
  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct CalcNumericTests {
  6    /// A random real number up to `scale` digits before the point: an integer, a fraction or
  7    /// a float, tiny to large.
  8    static func argument(_ generator: inout SeededGenerator, scale: Int = 6) -> String {
  9        let sign = Bool.random(using: &generator) ? "-" : ""
 10        let digits = Int.random(in: 1...9, using: &generator)
 11        let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(digits)
 12        switch Int.random(in: 0..<5, using: &generator) {
 13        case 0: return sign + String(Int.random(in: 0...(scale > 2 ? 720 : 70), using: &generator))
 14        case 1: return sign + "\(Int.random(in: 1...99, using: &generator)):\(Int.random(in: 2...99, using: &generator))"
 15        case 2: return sign + "\(mantissa)e\(Int.random(in: -30...(scale - mantissa.count), using: &generator))"
 16        case 3: return sign + "\(mantissa)e\(Int.random(in: -mantissa.count - 1...(scale - mantissa.count), using: &generator))"
 17        default: return sign + ["90.", "180.", "45", "30", "1.5707963267949", "3.14159265358979", "0.785398163397448", "1", "1.", "0.5",
 18                                "1e-10", "6.28318530717959", "7.", "7.00000000000001"].randomElement(using: &generator)!
 19        }
 20    }
 21
 22    /// A random number from -1 to 1.
 23    static func unit(_ generator: inout SeededGenerator) -> String {
 24        let sign = Bool.random(using: &generator) ? "-" : ""
 25        let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(Int.random(in: 1...9, using: &generator))
 26        switch Int.random(in: 0..<4, using: &generator) {
 27        case 0: return sign + ["0", "1", "1.", "0.5", "0.", "0.999999999999", "1e-10"].randomElement(using: &generator)!
 28        case 1:
 29            let d = Int.random(in: 2...99, using: &generator)
 30            return sign + "\(Int.random(in: 1..<d, using: &generator)):\(d)"
 31        case 2: return sign + "\(mantissa)e\(-mantissa.count - Int.random(in: 0...20, using: &generator))"
 32        default: return sign + "0.\(mantissa)"
 33        }
 34    }
 35
 36    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 37    func trigonometryMatchesCalc() throws {
 38        let seed = testSeed(20261122)
 39        var generator = SeededGenerator(state: seed)
 40        for precision in [3, 6, 8, 12, 14, 15, 16, 17, 18] {
 41            for radians in [false, true] {
 42                var cases: [(String, String)] = ["sin(nan)", "cos(nan)", "arctan(nan)", "tan(180)", "tan(-360)", "tan(0)", "arcsin(0)",
 43                                                 "arccos(1)", "arccos(0)", "arcsin(-1)", "arctan(1)", "sqrt(2)", "sqrt(1e-9)", "sin(-74250)", "cos(-74250)",
 44                                                 "sin(-360000000000090)", "cos(-90*4000000000001)", "tan(-360000000000180)"].map { ($0, "(float 0)") }
 45                for _ in 0..<500 {
 46                    let f = ["sin", "cos", "tan", "arcsin", "arccos", "arctan", "arctan2", "sinh", "cosh", "tanh", "sqrt"].randomElement(using: &generator)!
 47                    let x = switch f {
 48                    case "arcsin", "arccos": Self.unit(&generator)
 49                    case "arctan2": Self.argument(&generator) + "," + Self.argument(&generator)
 50                    case "sinh", "cosh", "tanh": Self.argument(&generator, scale: 1)
 51                    case "sqrt": Self.argument(&generator).replacingOccurrences(of: "-", with: "")
 52                    default: Self.argument(&generator)
 53                    }
 54                    cases.append(("\(f)(\(x))", "(float 0)"))
 55                }
 56                var modes = Calc.Modes()
 57                (modes.precision, modes.degrees, modes.format) = (precision, !radians, .float(0))
 58                var refused: [String] = []
 59                for (c, expected) in zip(cases, try CalcOracle.run(cases, precision: precision, radians: radians)) {
 60                    guard let ours = try? Calc.evaluate(c.0, modes: modes) else {
 61                        // Calc keeps a tangent of a quotient by zero unevaluated, and Calc's exp
 62                        // past 16 digits, worked out at two (four for tanh) digits more, isn't reproduced. Past
 63                        // 16 digits, two more don't always fit in a mantissa.
 64                        let name = String(c.0.prefix { $0 != "(" })
 65                        if precision <= 16, !expected.hasPrefix(name + "("), !(precision >= 13 && name == "tanh"), !(precision >= 15 && ["sinh", "cosh"].contains(name)) {
 66                            refused.append(c.0)
 67                        }
 68                        continue
 69                    }
 70                    #expect(ours == expected, "\(c.0) p\(precision) \(radians ? "rad" : "deg") seed \(seed)")
 71                }
 72                #expect(refused == [], "p\(precision) \(radians ? "rad" : "deg") \(refused) seed \(seed)")
 73            }
 74        }
 75    }
 76
 77    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 78    func zeroInEveryFormatMatchesCalc() throws {
 79        var cases: [(String, String)] = []
 80        for kind in ["float", "fix", "sci", "eng"] {
 81            for figs in [0, 1, 2, 3, 8, -2] {
 82                for e in ["0.", "-0.", "0.0", "1-1.0", "0./0", "0.e5", "0.001", "0.5", "-0.4", "4e-5", "123.456"] {
 83                    cases.append((e, "(\(kind) \(figs))"))
 84                }
 85            }
 86        }
 87        let skipped = try CalcTests.compare(cases)
 88        #expect(skipped == [], "\(skipped)")
 89    }
 90
 91    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 92    func fractionModeMatchesCalc() throws {
 93        let seed = testSeed(20261122)
 94        var generator = SeededGenerator(state: seed)
 95        let numbers = ["0", "1", "2", "3", "-2", "7", "10", "12", "1:2", "1:3", "-5:4", "7:2", "-3:7", "0.5", "2.5", "-1.5", "0.25", "3.", "1.2e1",
 96                       "100", "0.123456789", "0."]
 97        func number() -> String { numbers.randomElement(using: &generator)! }
 98        func vector() -> String { "[" + (0..<Int.random(in: 1...5, using: &generator)).map { _ in number() }.joined(separator: ",") + "]" }
 99        let unary = ["fact", "dfact", "abs", "floor", "ceil", "trunc", "round", "sqrt", "exp", "ln", "log10", "sin", "cos", "tan", "arcsin",
100                     "arccos", "arctan", "lnot", "percent", "float", "pfloat", "sign", "rounde", "roundu", "frac", "exp10", "sinh", "cosh",
101                     "tanh", "arcsinh", "arccosh", "arctanh", "deg", "rad"]
102        let binary = ["mod", "idiv", "max", "min", "round", "rounde", "roundu", "fdiv", "gcd", "lcm", "choose", "perm", "pow", "nroot",
103                      "hypot", "log", "arctan2", "eq", "lt", "land", "lor", "agmean"]
104        let statistics = ["vsum", "vprod", "vcount", "vmean", "vmax", "vmin", "vmedian", "vvar", "vpvar", "vsdev", "vpsdev", "vflat", "vgmean", "vhmean"]
105        var cases = ["vmedian([1,2])", "round(2.5,1)", "round(1:3,2)", "rounde(2.45,1)", "vmean([1,2])", "vmedian([1:3,1])", "7/2", "1/3+1/6",
106                     "2^-1", "0.5^-1", "(1:2)^0.5", "4^(1:2)", "8^(-1:3)", "7%2", "7\\2", "<2026-10-05 Mon>+1/2", "vsdev([1,2])",
107                     "round(3.,-2)", "round(-2.25,1)", "round(2.5,1.)", "mod(0,0.5)", "0%0.5", "vgmean([0.5])", "vgmean([1:4])"].map { ($0, "(float 12)") }
108        for _ in 0..<1500 {
109            switch Int.random(in: 0..<4, using: &generator) {
110            case 0: cases.append(("\(unary.randomElement(using: &generator)!)(\(number()))", "(float 12)"))
111            case 1: cases.append(("\(binary.randomElement(using: &generator)!)(\(number()),\(number()))", "(float 12)"))
112            case 2: cases.append(("\(statistics.randomElement(using: &generator)!)(\(vector()))", "(float 12)"))
113            default:
114                let op = ["+", "-", "*", "/", "^", "%", "\\"].randomElement(using: &generator)!
115                cases.append(("(\(number()))\(op)(\(number()))", "(float 12)"))
116            }
117        }
118        for fractions in [true, false] { _ = try CalcTests.compare(cases, fractions: fractions, note: " seed \(seed)") }
119    }
120
121    /// `math-mod` divides as a float, without F, unless both operands are natural numbers.
122    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
123    func modOfNegativeIntegersMatchesCalc() throws {
124        let cases = ["(-74251)%4", "mod(74251,-4)", "mod(-1234567890123457,4)", "(-1234567890123457)%7", "mod(-7,2)", "mod(7,-2)",
125                     "(-7)%(-2)", "mod(1234567890123457,4)", "(-1234567890123457)\\4", "mod(-7:2,2)", "mod(-1:3,-1:7)"].map { ($0, "(float 0)") }
126        for precision in [3, 12] {
127            for fractions in [true, false] {
128                let skipped = try CalcTests.compare(cases, precision: precision, fractions: fractions)
129                #expect(skipped == [], "p\(precision) \(skipped)")
130            }
131        }
132        let wide = ["mod(-1234567890123456789,7)", "(-1234567890123456789)%7", "mod(1234567890123456789,-7)", "mod(-29999999999999999,-10)",
133                    "(-29999999999999999)%(-10)", "mod(-9999999999999999,-10)"].map { ($0, "(float 0)") }
134        for precision in [16, 17, 18] {
135            for fractions in [true, false] {
136                let skipped = try CalcTests.compare(wide, precision: precision, fractions: fractions)
137                #expect(skipped == [], "p\(precision) \(skipped)")
138            }
139        }
140    }
141
142    /// Calc's `math-overflow` and `math-underflow` past an exponent of 4,000,000 leave the formula alone.
143    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
144    func floatOverflowIsRefusedAsCalcDoes() throws {
145        let refused = ["2.5^123456789012", "pow(-1.5,123456789012)", "pow(1e20,123456789012)", "0.4^123456789012", "2.5^(-123456789012)"]
146        let cases = (refused + ["2.5^1000000", "0.4^1000000"]).map { ($0, "(float 0)") }
147        for fractions in [true, false] {
148            let skipped = try CalcTests.compare(cases, fractions: fractions)
149            #expect(skipped == refused)
150        }
151    }
152
153    /// Vector results, with and without `N`, zero with no decimal places, and fractions.
154    static let tables = [
155        "| 1 | 2 | | |\n|---+---+---+---|\n| 2.5 | 0.25 | | |\n#+TBLFM: $3=vmedian($1..$2);F::$4=round($1,1);F\n",
156        "| 1 | 2 | |\n|---+---+---|\n| 3 | x | |\n| 1.5 | 0. | |\n#+TBLFM: $3=$1..$2;N\n",
157        "| 1 | 2 | |\n|---+---+---|\n| 1.5 | 0. | |\n| 1:3 | -2 | |\n#+TBLFM: $3=$1..$2\n",
158        "| 1.5 | 0 | |\n|---+---+---|\n| 2 | 4 | |\n#+TBLFM: $3=$1..$2;Nf0\n",
159        "| 1 | 2 | |\n|---+---+---|\n| 3 | 4 | |\n#+TBLFM: @1$3=@1$1..@2$2;N::@2$3=vflat(@1$1..@2$2);N\n",
160        "| 1 | 2 | |\n#+TBLFM: $3=[$1, [$2]];N\n",
161        "| 0 | | | |\n|---+---+---+---|\n| 0.5 | | | |\n#+TBLFM: $2=$1*1.0;f0::$3=($1-$1)*1.;s2::$4=($1-$1)*1./0;f0\n",
162    ]
163
164    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
165    func vectorsAndZeroInTablesMatchEmacsNatively() throws {
166        try TableFormulaTests().compare(Self.tables, fallbacksAllowed: false, headerFallbacksAllowed: false)
167    }
168}