Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXExpression/Tests/ORIXExpressionTests/EngineTests.swift3// Description: Reference tests for parsing, exact arithmetic, scientific functions, complex numbers, matrices, formatting and RPN.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import BigInt10@testable import ORIXExpression1112func calc(_ s: String, _ configure: (inout CalculatorEngine) -> Void = { _ in }) throws -> String {13 var e = CalculatorEngine()14 configure(&e)15 let r = try e.run(s)16 var f = e.format17 f.angleMode = e.context.angleMode18 return NumberFormatting.format(r.value!, f)19}20func num(_ s: String, _ configure: (inout CalculatorEngine) -> Void = { _ in }) throws -> Double {21 var e = CalculatorEngine()22 configure(&e)23 return try #require(try e.run(s).value?.doubleValue)24}25func close(_ a: Double, _ b: Double, _ tol: Double = 1e-12) -> Bool { abs(a - b) <= tol * max(1, abs(b)) }26let degrees: @Sendable (inout CalculatorEngine) -> Void = { $0.context.angleMode = .degrees }27let complexMode: @Sendable (inout CalculatorEngine) -> Void = { $0.context.complexEnabled = true }2829@Suite struct StandardArithmetic {30 @Test func basics() throws {31 #expect(try calc("25 × 4") == "100")32 #expect(try calc("7 − 10") == "−3")33 #expect(try calc("1 ÷ 4") == "0.25")34 #expect(try calc("2 + 3 * 4") == "14")35 #expect(try calc("(2 + 3) * 4") == "20")36 #expect(try calc("2 ^ 3 ^ 2") == "512")37 #expect(try calc("-2 ^ 2") == "−4")38 #expect(try calc("(-2) ^ 2") == "4")39 #expect(try calc("2 ^ -2") == "0.25")40 #expect(try calc("10 - 2 - 3") == "5")41 #expect(try calc("100 / 10 / 5") == "2")42 #expect(try calc("6 ÷ 2(1 + 2)") == "9")43 #expect(try calc("--5") == "5")44 #expect(try calc("2 * -3") == "−6")45 }46 @Test func decimalsAreExact() throws {47 #expect(try calc("0.1 + 0.2") == "0.3")48 #expect(try calc("0.1 * 3") == "0.3")49 #expect(try calc("1.1 * 1.1") == "1.21")50 #expect(try calc("0.1 + 0.2 == 0.3") == "true")51 #expect(try calc("1 - 0.9") == "0.1")52 #expect(try calc("4.35 * 100") == "435")53 #expect(try calc("1/3 + 1/3 + 1/3") == "1")54 #expect(try calc("1/3") == "0.333333333333")55 #expect(try calc("2/3") == "0.666666666667")56 #expect(try calc("1e-7 * 1e-7") == "1×10⁻¹⁴" || (try calc("1e-7 * 1e-7")) == "0.00000000000001")57 }58 @Test func percentConvention() throws {59 #expect(try calc("200 + 10%") == "220")60 #expect(try calc("200 - 10%") == "180")61 #expect(try calc("200 * 10%") == "20")62 #expect(try calc("200 / 10%") == "2000")63 #expect(try calc("50%") == "0.5")64 #expect(try calc("100 + 5% + 5%") == "110.25")65 #expect(try calc("200 + 10%") { $0.context.percentMode = .strict } == "200.1")66 #expect(try calc("(100 + 50) - 20%") == "120")67 }68 @Test func largeAndSmall() throws {69 #expect(try calc("2^100") == "1267650600228229401496703205376")70 #expect(try calc("20!") == "2432902008176640000")71 #expect(try calc("25!") == "15511210043330985984000000")72 #expect(try calc("99999999999999999999 + 1") == "100000000000000000000")73 #expect(try calc("2^-20") == "0.00000095367431640625")74 #expect(try calc("1e400 / 1e399") == "10")75 #expect(try calc("100!").hasPrefix("9.33262154439×10¹⁵⁷"))76 #expect(try calc("123456789 * 987654321") == "121932631112635269")77 }78 @Test func errors() throws {79 #expect(throws: CalcError.divisionByZero) { try calc("1/0") }80 #expect(throws: CalcError.divisionByZero) { try calc("5 mod 0") }81 #expect(throws: CalcError.divisionByZero) { try calc("0^-1") }82 #expect(throws: CalcError.self) { try calc("2 +") }83 #expect(throws: CalcError.self) { try calc("2 + * 3") }84 #expect(throws: CalcError.self) { try calc("(2 + 3))") }85 #expect(throws: CalcError.unknownVariable("foo")) { try calc("foo + 1") }86 #expect(throws: CalcError.self) { try calc("") }87 #expect(throws: CalcError.self) { try calc("1e308 * 1e308 * 0.5 + exp(1000)") }88 #expect(throws: CalcError.self) { try calc("exp(1000)") }89 #expect(throws: CalcError.self) { try calc("sin(1, 2)") }90 #expect(throws: CalcError.self) { try calc("pi = 3") }91 }92 @Test func negativeZeroIsNormalised() throws {93 #expect(try calc("-0") == "0")94 #expect(try calc("0 * -5.5") == "0")95 #expect(try calc("-(1e-200 * 1e-200 * sqrt(2))") == "0")96 }97 @Test func variablesAndAns() throws {98 var e = CalculatorEngine()99 try e.run("x = 5")100 try e.run("y = x^2 + 1")101 #expect(try e.run("y / 2").value == Value(13))102 #expect(try e.run("ans + 1").value == Value(14))103 try e.run("f(a, b) = a^2 + b")104 #expect(try e.run("f(3, 1)").value == Value(10))105 #expect(throws: CalcError.self) { try e.run("g(a) = a + undefinedThing") }106 }107 @Test func implicitMultiplication() throws {108 var e = CalculatorEngine()109 try e.run("x = 3")110 #expect(try e.run("2x").value == Value(6))111 #expect(try e.run("2x^2").value == Value(18))112 #expect(try e.run("x(x + 1)").value == Value(12))113 #expect(try e.run("(x + 1)(x - 1)").value == Value(8))114 #expect(close(try e.run("2π").value!.doubleValue!, 2 * .pi))115 #expect(close(try e.run("2 sin(x)").value!.doubleValue!, 2 * sin(3)))116 #expect(try e.run("x²").value == Value(9))117 #expect(try e.run("2x³").value == Value(54))118 #expect(try e.run("√16").value == Value(4))119 #expect(try e.run("|x - 5|").value == Value(2))120 #expect(close(try e.run("sin 2x").value!.doubleValue!, sin(6)))121 }122 @Test func localeInput() throws {123 var e = CalculatorEngine()124 e.format.decimalSeparator = ","125 #expect(try e.run("1,5 + 2,25").value == Value(BigRational(15, 4)))126 #expect(try e.run("max(1,5; 2,5)").value == Value(BigRational(5, 2)))127 #expect(NumberFormatting.format(try e.run("1,5 + 2,25").value!, e.format) == "3,75")128 }129}130131@Suite struct Scientific {132 @Test func exactSpecialAngles() throws {133 #expect(try calc("sin(30)", degrees) == "0.5")134 #expect(try calc("cos(60)", degrees) == "0.5")135 #expect(try calc("sin(180)", degrees) == "0")136 #expect(try calc("cos(90)", degrees) == "0")137 #expect(try calc("tan(45)", degrees) == "1")138 #expect(try calc("tan(135)", degrees) == "−1")139 #expect(try calc("sin(-90)", degrees) == "−1")140 #expect(try calc("sin(pi)") == "0")141 #expect(try calc("cos(pi/2)") == "0")142 #expect(try calc("cos(pi)") == "−1")143 #expect(try calc("sin(100)") { $0.context.angleMode = .gradians } == "1")144 #expect(try calc("asin(1)", degrees) == "90")145 #expect(try calc("acos(0.5)", degrees) == "60")146 #expect(try calc("atan(1)", degrees) == "45")147 #expect(try calc("sin(30°)") == "0.5")148 #expect(throws: CalcError.self) { try calc("tan(90)", degrees) }149 #expect(throws: CalcError.self) { try calc("tan(pi/2)") }150 }151 @Test func identities() throws {152 for x in [0.3, 1.7, -2.4, 10.5] {153 #expect(close(try num("sin(\(x))^2 + cos(\(x))^2"), 1))154 #expect(close(try num("tan(\(x)) - sin(\(x))/cos(\(x))"), 0, 1e-12))155 #expect(close(try num("sinh(\(x / 4))^2 - cosh(\(x / 4))^2"), -1, 1e-9))156 #expect(close(try num("exp(ln(\(abs(x))))"), abs(x)))157 #expect(close(try num("ln(\(abs(x)) * 3) - ln(\(abs(x))) - ln(3)"), 0, 1e-12))158 #expect(close(try num("asin(sin(0.3))"), 0.3))159 }160 }161 @Test func exactRootsAndLogs() throws {162 #expect(try calc("sqrt(16)") == "4")163 #expect(try calc("sqrt(1/4)") == "0.5")164 #expect(try calc("sqrt(2)") == "1.41421356237")165 #expect(try calc("cbrt(-27)") == "−3")166 #expect(try calc("root(32, 5)") == "2")167 #expect(try calc("8^(1/3)") == "2")168 #expect(try calc("(-8)^(1/3)") == "−2")169 #expect(try calc("27^(2/3)") == "9")170 #expect(try calc("log(1000)") == "3")171 #expect(try calc("log2(1/8)") == "−3")172 #expect(try calc("log(81, 3)") == "4")173 #expect(try calc("ln(1)") == "0")174 #expect(try calc("exp(0)") == "1")175 #expect(close(try num("ln(e)"), 1))176 #expect(close(try num("log(2)"), 0.301029995663981195))177 }178 @Test func domainErrors() throws {179 #expect(throws: CalcError.self) { try calc("sqrt(-1)") }180 #expect(throws: CalcError.self) { try calc("ln(0)") }181 #expect(throws: CalcError.self) { try calc("ln(-1)") }182 #expect(throws: CalcError.self) { try calc("asin(2)") }183 #expect(throws: CalcError.self) { try calc("acosh(0.5)") }184 #expect(throws: CalcError.self) { try calc("(-2)^0.5") }185 #expect(throws: CalcError.self) { try calc("(-3)!") }186 #expect(throws: CalcError.self) { try calc("gamma(0)") }187 #expect(throws: CalcError.self) { try calc("log(5, 1)") }188 #expect(throws: CalcError.self) { try calc("0/0") }189 }190 @Test func combinatoricsAndNumberTheory() throws {191 #expect(try calc("nCr(52, 5)") == "2598960")192 #expect(try calc("nPr(10, 3)") == "720")193 #expect(try calc("nCr(100, 50)") == "100891344545564193334812497256")194 #expect(try calc("nCr(5, 7)") == "0")195 #expect(try calc("gcd(84, 36)") == "12")196 #expect(try calc("lcm(4, 6, 10)") == "60")197 #expect(try calc("17 mod 5") == "2")198 #expect(try calc("-7 mod 3") == "2")199 #expect(try calc("7.5 mod 2") == "1.5")200 #expect(try calc("isprime(2^61 - 1)") == "true")201 #expect(try calc("isprime(2^89 - 1)") == "true")202 #expect(try calc("isprime(2^67 - 1)") == "false")203 #expect(try calc("factor(600851475143)") == "[71, 839, 1471, 6857]")204 #expect(try calc("factor(18446744073709551557)") == "[18446744073709551557]")205 #expect(try calc("fib(90)") == "2880067194370816120")206 #expect(close(try num("0.5!"), 0.886226925452758014))207 #expect(close(try num("gamma(5.5)"), 52.3427777845535208))208 }209 @Test func rounding() throws {210 #expect(try calc("round(2.5)") == "3")211 #expect(try calc("round(-2.5)") == "−3")212 #expect(try calc("round(2.675, 2)") == "2.68")213 #expect(try calc("round(1234.5678, -2)") == "1200")214 #expect(try calc("floor(-2.5)") == "−3")215 #expect(try calc("ceil(2.1)") == "3")216 #expect(try calc("trunc(-2.7)") == "−2")217 #expect(try calc("frac(2.75)") == "0.75")218 #expect(try calc("abs(-7/2)") == "3.5")219 }220 @Test func numericalCalculus() throws {221 #expect(close(try num("integral(x^2, x, 0, 3)"), 9, 1e-10))222 #expect(close(try num("integral(exp(-x^2), x, -inf, inf)"), sqrt(Double.pi), 1e-9))223 #expect(close(try num("integral(1/sqrt(x), x, 0, 1)"), 2, 1e-7))224 #expect(close(try num("integral(sin(x), x, 0, pi)"), 2, 1e-10))225 #expect(close(try num("deriv(sin(x), x, 0)"), 1, 1e-9))226 #expect(close(try num("deriv(x^3, x, 2)"), 12, 1e-8))227 #expect(close(try num("nsolve(x^2 = 2, x, 0, 2)"), 2.0.squareRoot(), 1e-12))228 #expect(close(try num("nsolve(cos(x) - x, x, 1)"), 0.739085133215160642, 1e-12))229 #expect(try calc("sum(k^2, k, 1, 100)") == "338350")230 #expect(try calc("sum(1/k, k, 1, 10)") == "2.92896825397")231 #expect(try calc("prod(k, k, 1, 10)") == "3628800")232 #expect(throws: CalcError.self) { try calc("nsolve(x^2 + 1, x, -1, 1)") }233 #expect(throws: CalcError.self) { try calc("integral(1/x, x, 0, 1)") }234 }235 @Test func logicAndPiecewise() throws {236 #expect(try calc("if(3 > 2, 10, 20)") == "10")237 #expect(try calc("piecewise(1 > 2, 5, 2 > 1, 7, 9)") == "7")238 #expect(try calc("1 < 2 < 3") == "true")239 #expect(try calc("3 >= 4 or 1 != 2") == "true")240 }241 @Test func constants() throws {242 #expect(close(try num("_c"), 299_792_458))243 #expect(close(try num("_R"), 8.31446261815324))244 #expect(close(try num("phi^2 - phi"), 1))245 #expect(close(try num("tau"), 2 * .pi))246 }247}248249@Suite struct ComplexNumbers {250 @Test func arithmetic() throws {251 #expect(try calc("i^2", complexMode) == "−1")252 #expect(try calc("(1 + 2i)(3 - i)", complexMode) == "5 + 5i")253 #expect(try calc("(1 + 2i) / (3 - 4i)", complexMode) == "−0.2 + 0.4i")254 #expect(try calc("sqrt(-4)", complexMode) == "2i")255 #expect(try calc("abs(3 + 4i)", complexMode) == "5")256 #expect(try calc("conj(3 + 4i)", complexMode) == "3 − 4i")257 #expect(try calc("re(3 + 4i) + im(3 + 4i)", complexMode) == "7")258 #expect(try calc("exp(i pi) + 1", complexMode).hasPrefix("1.22464679915×10⁻¹⁶i") || (try calc("exp(i pi) + 1", complexMode)) == "0")259 #expect(try calc("ln(-1)", complexMode) == "3.14159265359i")260 #expect(try calc("(-8)^(1/3)", complexMode) == "1 + 1.73205080757i")261 #expect(throws: CalcError.self) { try calc("1 + i") }262 }263 @Test func polar() throws {264 let both: (inout CalculatorEngine) -> Void = { $0.context.complexEnabled = true; $0.context.angleMode = .degrees }265 #expect(try calc("polar(2, 90)", both) == "2i")266 #expect(try calc("arg(1 + i)", both) == "45")267 #expect(try calc("3 + 4i") { both(&$0); $0.format.complexForm = .polar } == "5∠53.1301023542°")268 }269}270271@Suite struct Matrices {272 @Test func exactAlgebra() throws {273 #expect(try calc("det([1, 2; 3, 4])") == "−2")274 #expect(try calc("inv([1, 2; 3, 4])") == "[−2, 1; 1.5, −0.5]")275 #expect(try calc("[1, 2; 3, 4] * [5, 6; 7, 8]") == "[19, 22; 43, 50]")276 #expect(try calc("[1, 2; 3, 4]^2") == "[7, 10; 15, 22]")277 #expect(try calc("[1, 2; 3, 4]^-1 * [1, 2; 3, 4]") == "[1, 0; 0, 1]")278 #expect(try calc("transpose([1, 2, 3; 4, 5, 6])") == "[1, 4; 2, 5; 3, 6]")279 #expect(try calc("det([2, 0, 1; 1, 3, 2; 1, 1, 2])") == "6")280 #expect(try calc("rank([1, 2, 3; 2, 4, 6; 1, 0, 1])") == "2")281 #expect(try calc("rref([1, 2, 3; 4, 5, 6])") == "[1, 0, −1; 0, 1, 2]")282 #expect(try calc("solve([2, 1; 1, 3], [3, 5])") == "[0.8, 1.4]")283 #expect(try calc("tr([1, 2; 3, 4])") == "5")284 #expect(try calc("[[1, 2], [3, 4]] + identity(2)") == "[2, 2; 3, 5]")285 // Hilbert matrix: exact arithmetic gives the exact determinant 1/2160286 #expect(try calc("det([1, 1/2, 1/3; 1/2, 1/3, 1/4; 1/3, 1/4, 1/5]) * 2160") == "1")287 }288 @Test func vectors() throws {289 #expect(try calc("dot([1, 2, 3], [4, 5, 6])") == "32")290 #expect(try calc("cross([1, 0, 0], [0, 1, 0])") == "[0, 0, 1]")291 #expect(try calc("norm([3, 4])") == "5")292 #expect(try calc("[1, 2, 3] + [10, 20, 30]") == "[11, 22, 33]")293 #expect(try calc("2 * [1, 2, 3]") == "[2, 4, 6]")294 #expect(try calc("mean([1, 2, 3, 4])") == "2.5")295 #expect(try calc("stdev([2, 4, 4, 4, 5, 5, 7, 9])") == "2.1380899353")296 #expect(try calc("pstdev([2, 4, 4, 4, 5, 5, 7, 9])") == "2")297 #expect(try calc("median([5, 1, 3, 2])") == "2.5")298 #expect(try calc("[1, 2; 3, 4] * [1, 1]") == "[3, 7]")299 }300 @Test func errorsAndEigenvalues() throws {301 #expect(throws: CalcError.self) { try calc("inv([1, 2; 2, 4])") }302 #expect(throws: CalcError.self) { try calc("det([1, 2, 3; 4, 5, 6])") }303 #expect(throws: CalcError.self) { try calc("[1, 2; 3, 4] * [1, 2, 3; 4, 5, 6; 7, 8, 9]") }304 #expect(throws: CalcError.self) { try calc("solve([1, 1; 1, 1], [1, 2])") }305 #expect(throws: CalcError.self) { try calc("[1, 2] * [3, 4]") }306 #expect(try calc("eig([2, 0; 0, 3])") == "[3, 2]")307 #expect(try calc("eig([2, 1; 1, 2])") == "[3, 1]")308 #expect(try calc("eig([0, -1; 1, 0])", complexMode) == "[i, −i]")309 #expect(throws: CalcError.self) { try calc("eig([0, -1; 1, 0])") }310 let v = try num("max(eig([4, 1, 2; 1, 3, 0; 2, 0, 5]))")311 #expect(close(v, 6.669079088282288, 1e-10))312 }313}314315@Suite struct Formatting {316 func fmt(_ s: String, _ c: (inout NumberFormat) -> Void) throws -> String {317 try calc(s) { c(&$0.format) }318 }319 @Test func notations() throws {320 #expect(try fmt("1234567.891") { $0.groupingSeparator = "," } == "1,234,567.891")321 #expect(try fmt("1234567,891") { $0.groupingSeparator = " "; $0.decimalSeparator = "," } == "1 234 567,891")322 #expect(try fmt("123456") { $0.notation = .scientific } == "1.23456×10⁵")323 #expect(try fmt("123456") { $0.notation = .engineering } == "123.456×10³")324 #expect(try fmt("0.000123") { $0.notation = .engineering } == "123×10⁻⁶")325 #expect(try fmt("123456") { $0.notation = .scientific; $0.exponentStyle = .e } == "1.23456e5")326 #expect(try fmt("2/3") { $0.decimalPlaces = 2 } == "0.67")327 #expect(try fmt("5") { $0.decimalPlaces = 2 } == "5.00")328 #expect(try fmt("1.005") { $0.decimalPlaces = 2 } == "1.01")329 #expect(try fmt("-0.001") { $0.decimalPlaces = 2 } == "0.00")330 #expect(try fmt("2/3") { $0.significantDigits = 4 } == "0.6667")331 #expect(try fmt("3/4") { $0.showFractions = true } == "3/4")332 #expect(try fmt("1/3 + 1/6") { $0.showFractions = true } == "1/2")333 #expect(try fmt("pi * 1e20") { _ in } == "3.14159265359×10²⁰")334 #expect(try fmt("pi / 1e10") { _ in } == "3.14159265359×10⁻¹⁰")335 #expect(try fmt("sqrt(2) * 1000000") { _ in } == "1414213.56237")336 #expect(try fmt("123456") { $0.notation = .scientific; $0.decimalPlaces = 2 } == "1.23×10⁵")337 }338 @Test func displayNeverChangesTheValue() throws {339 var e = CalculatorEngine()340 e.format.decimalPlaces = 2341 try e.run("x = 2/3")342 #expect(try e.run("x * 3").value == Value(2))343 }344 @Test func canonicalRoundTrip() throws {345 for s in ["1/3", "0.1", "2^70", "sqrt(2)", "-5/7", "1e-9 * pi"] {346 let v = try CalculatorEngine().evaluate(s)347 let text = NumberFormatting.format(v, .canonical)348 #expect(try CalculatorEngine().evaluate(text) == v || close(try CalculatorEngine().evaluate(text).doubleValue!, v.doubleValue!, 0))349 }350 }351 @Test func doubleRoundingIsCorrect() {352 #expect(BigRational(1, 3).doubleValue == 1.0 / 3.0)353 #expect(BigRational(decimalLiteral: "0.1")!.doubleValue == 0.1)354 #expect(BigRational(decimalLiteral: "1e308")!.doubleValue == 1e308)355 #expect(BigRational(decimalLiteral: "1e309")!.doubleValue == .infinity)356 #expect(BigRational(decimalLiteral: "4.9e-324")!.doubleValue == 4.9e-324)357 #expect(BigRational(decimalLiteral: "2.2250738585072014e-308")!.doubleValue == 2.2250738585072014e-308)358 #expect(BigRational(decimalLiteral: "9007199254740993")!.doubleValue == 9007199254740992)359 #expect(BigRational(decimalLiteral: "1.7976931348623157e308")!.doubleValue == Double.greatestFiniteMagnitude)360 for x in [0.1, 1e-300, 123456.789, 5e-324, Double.pi, -2.5e17] { #expect(BigRational(exactly: x)!.doubleValue == x) }361 }362 @Test func printer() throws {363 let e = try Parser.parse("2*x^2 - sqrt(x)/3 + sin(pi*x)")364 #expect(Printer.string(e) == "2x² − √(x)/3 + sin(π · x)")365 #expect(Printer.string(e, style: .latex) == "2x^{2} - \\frac{\\sqrt{x}}{3} + \\sin\\left(\\pi \\cdot x\\right)")366 let ascii = Printer.string(e, style: .ascii)367 #expect(try Parser.parse(ascii) == e)368 for s in ["-(a+b)^2", "a/(b*c)", "a-(b-c)", "(a^b)^c", "2^(-x)", "-x^2", "(1/2)*x", "a*(b+c)/d", "x!", "(x+1)!"] {369 let parsed = try Parser.parse(s)370 #expect(try Parser.parse(Printer.string(parsed, style: .ascii)) == parsed, "round trip of \(s)")371 }372 }373}374375@Suite struct Verification {376 @Test func exactVersusFloating() throws {377 var e = CalculatorEngine()378 #expect(try e.run("1/3 + 1/6").isExact)379 #expect(!(try e.run("sqrt(2)").isExact))380 #expect(try e.run("1/3 + 1/6").verification.isVerified)381 }382 @Test func cancellationIsReported() throws {383 var e = CalculatorEngine()384 let r = try e.run("(sqrt(2) * 1e9 + 1e-3) - sqrt(2) * 1e9")385 #expect(r.verification.warnings.contains { $0.kind == .stability })386 #expect(!r.verification.isVerified)387 }388 @Test func explanationRecordsRealSteps() throws {389 var e = CalculatorEngine()390 let r = try e.run("2 + 3 * 4")391 #expect(r.explanation.steps.map(\.expression) == ["3 × 4", "2 + 12"])392 #expect(r.explanation.steps.map(\.value) == ["12", "14"])393 let p = try e.run("200 + 10%")394 #expect(p.explanation.assumptions.contains { $0.contains("Percent convention") })395 }396}397398@Suite struct RPN {399 @Test func stack() throws {400 var m = RPNMachine()401 try m.enter("3"); try m.enter("4"); try m.apply(.add)402 try m.enter("5"); try m.apply(.multiply)403 #expect(m.x == Value(35))404 try m.enter("2"); try m.apply(.swap); try m.apply(.divide)405 #expect(m.x == Value(BigRational(2, 35)))406 try m.apply(.clear)407 try m.enter("200"); try m.enter("10"); try m.apply(.percent)408 #expect(m.stack == [Value(200), Value(20)])409 try m.apply(.add)410 #expect(m.x == Value(220))411 try m.applyFunction("sqrt")412 #expect(close(m.x!.doubleValue!, 220.0.squareRoot()))413 #expect(throws: CalcError.self) { try m.apply(.add) }414 #expect(m.stack.count == 1)415 }416}417418@Suite struct Compiled {419 @Test func matchesEvaluator() throws {420 let e = try Parser.parse("sin(x)^2 + exp(-x/3) * sqrt(abs(x)) - x^3/(1 + x^2)")421 let f = try CompiledExpression(e, variables: ["x"])422 for x in [-3.2, -1, 0.5, 2, 7.7] {423 var ctx = EvalContext()424 ctx.variables["x"] = Value(x)425 let reference = try Evaluator(context: ctx).evaluate(e).doubleValue!426 #expect(close(f(x), reference, 1e-13))427 }428 }429 @Test func undefinedIsNaN() throws {430 #expect(try CompiledExpression(Parser.parse("sqrt(x)"), variables: ["x"])(-1).isNaN)431 #expect(try CompiledExpression(Parser.parse("1/x"), variables: ["x"])(0).isNaN)432 #expect(try CompiledExpression(Parser.parse("ln(x)"), variables: ["x"])(0).isNaN)433 #expect(try CompiledExpression(Parser.parse("x^(1/3)"), variables: ["x"])(-8) == -2)434 #expect(try CompiledExpression(Parser.parse("piecewise(x < 0, -x, x >= 0, x^2)"), variables: ["x"])(3) == 9)435 #expect(try CompiledExpression(Parser.parse("sum(k*x, k, 1, 4)"), variables: ["x"])(2) == 20)436 let f = try CompiledExpression(Parser.parse("integral(t^2, t, 0, x)"), variables: ["x"])437 #expect(close(f(3), 9, 1e-9))438 }439 @Test func splitIdentifiers() throws {440 let e = try Parser.parse("xy + 2ab", options: ParserOptions(splitUnknownIdentifiers: true))441 #expect(e.variables == ["x", "y", "a", "b"])442 }443}444445@Suite struct Regression {446 /// Reported by the graph engine: an equation whose left side is a built-in call was read as a definition.447 @Test func equationWithBuiltinOnTheLeft() throws {448 guard case .expression(.binary(.equal, _, _)) = try Parser.parseStatement("sin(x) = cos(y)") else { Issue.record("not an equation"); return }449 guard case .expression(.binary(.equal, _, _)) = try Parser.parseStatement("xy = 1", options: ParserOptions(splitUnknownIdentifiers: true)) else { Issue.record("not an equation"); return }450 guard case .assignment("xy", _) = try Parser.parseStatement("xy = 1") else { Issue.record("not an assignment"); return }451 #expect(throws: CalcError.self) { try Parser.parseStatement("pi = 3") }452 }453 /// Reported by the symbolic engine: long sums overflowed the 512 KB stack of a secondary thread.454 @Test func longChainsOnASmallStack() async throws {455 let terms = (1...900).map(String.init).joined(separator: " + ")456 let value: Value = try await Task.detached {457 var engine = CalculatorEngine()458 let r = try engine.run(terms)459 _ = try CompiledExpression(Parser.parse(terms + " + x"), variables: ["x"])(1)460 return r.value!461 }.value462 #expect(value == Value(900 * 901 / 2))463 #expect(throws: CalcError.self) { try Parser.parse((1...6000).map(String.init).joined(separator: "+")) }464 }465}466