Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Calc9// File : Packages/ORIXSymbolic/Tests/ORIXSymbolicTests/StructuralTests.swift10// Description : Exact structural expectations, honest unsupported paths,11// angle-mode policy, explanations, bounds and performance.12// Module : ORIXSymbolicTests13// 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 Testing92import BigInt93import ORIXExpression94import ORIXNumerics95@testable import ORIXSymbolic9697func simp(_ s: String, _ o: SymbolicOptions = .standard) -> String { Symbolic.simplify(P(s), options: o).text }98func diff(_ s: String, _ v: String = "x", order: Int = 1) -> String { Symbolic.differentiate(P(s), variable: v, order: order).text }99func integ(_ s: String) -> String { Symbolic.integrate(P(s), variable: "x").text(style: .pretty, constantOfIntegration: false) }100101@Suite struct CanonicalForms {102 @Test func likeTermsAndPowers() {103 #expect(simp("x + x") == "2x")104 #expect(simp("x*x") == "x²")105 #expect(simp("x^2*x^3") == "x⁵")106 #expect(simp("x^a*x^b") == "x^(a + b)")107 #expect(simp("x - x") == "0")108 #expect(simp("x^0") == "1")109 #expect(simp("x^1") == "x")110 #expect(simp("-(-x)") == "x")111 #expect(simp("2(x+1)") == "2x + 2")112 #expect(simp("3x^2 - 2x + 1 - x^3") == "−x³ + 3x² − 2x + 1")113 #expect(simp("x + sin(x) + 1 + x^2") == "x² + x + sin(x) + 1")114 #expect(simp("1/3 + 1/6") == "1/2")115 #expect(simp("0.1 + 0.2") == "3/10")116 #expect(simp("x/2 + x/3") == "5x/6")117 }118 @Test func quotients() {119 #expect(simp("(x^2-1)/(x-1)") == "x + 1")120 #expect(simp("(2x+2)/(x+1)") == "2")121 #expect(simp("x*(x+1)/x") == "x + 1")122 #expect(simp("(1-x)/(x-1)") == "−1")123 #expect(simp("1/x + 1/x") == "2/x")124 #expect(simp("x^-2") == "1/x²")125 }126 @Test func identitiesThatAreAlwaysValid() {127 #expect(simp("sin(x)^2 + cos(x)^2") == "1")128 #expect(simp("3sin(2x)^2 + 3cos(2x)^2 + x") == "x + 3")129 #expect(simp("cosh(x)^2 - sinh(x)^2") == "1")130 #expect(simp("exp(ln(x))") == "x")131 #expect(simp("ln(e^x)") == "x")132 #expect(simp("ln(1)") == "0")133 #expect(simp("sqrt(x)^2") == "x")134 #expect(simp("e^x*e^(2x)") == "exp(3x)")135 #expect(simp("sin(-x)") == "−sin(x)")136 #expect(simp("cos(-x)") == "cos(x)")137 #expect(simp("sin(pi/6)") == "1/2")138 #expect(simp("cos(pi/4)") == "√(2)/2")139 #expect(simp("sqrt(8)") == "2√(2)")140 #expect(simp("ln(8)/ln(2)") == "3")141 #expect(simp("i^2") == "−1")142 }143 @Test func assumptionsAreRequiredForBranchSensitiveRules() {144 // without assumptions these are NOT rewritten145 #expect(simp("sqrt(x^2)") == "|x|")146 #expect(simp("ln(x*y)") == "ln(x · y)")147 #expect(simp("ln(x^2)") == "ln(x²)")148 let positive = SymbolicOptions(assumePositive: true)149 #expect(simp("sqrt(x^2)", positive) == "x")150 #expect(simp("ln(x*y)", positive) == "ln(x) + ln(y)")151 #expect(simp("ln(x^2)", positive) == "2ln(x)")152 #expect(simp("abs(x)", positive) == "x")153 #expect(simp("abs(x-1)", positive) == "|x − 1|") // x − 1 is not known to be positive154 let r = Symbolic.simplify(P("sqrt(x^2)"), options: positive)155 #expect(r.explanation.assumptions.contains { $0.contains("positive") })156 }157 @Test func expandAndFactor() {158 #expect(Symbolic.expand(P("(x+1)^3")).text == "x³ + 3x² + 3x + 1")159 #expect(Symbolic.expand(P("(x+1)(x-1)")).text == "x² − 1")160 #expect(Symbolic.expand(P("(a+b)^2")).text == "a² + 2a · b + b²")161 #expect(Symbolic.factor(P("x^2-1")).text == "(x + 1) · (x − 1)")162 #expect(Symbolic.factor(P("2x^3+4x^2+2x")).text == "2x · (x + 1)²")163 #expect(Symbolic.factor(P("x^4+4")).text == "(x² + 2x + 2) · (x² − 2x + 2)")164 let irreducible = Symbolic.factor(P("x^2+1"))165 #expect(irreducible.text == "x² + 1" && irreducible.note.contains("irreducible"))166 #expect(Symbolic.factor(P("x*y + x")).kind == .unsupported)167 #expect(Symbolic.factor(P("sin(x)^2 - 1")).kind == .unsupported)168 #expect(Symbolic.expand(P("(x+y+z+1)^40")).kind == .unsupported) // bounded: refuses instead of blowing up169 }170 @Test func resultKinds() {171 #expect(Symbolic.simplify(P("2+3")).kind == .exact)172 #expect(Symbolic.simplify(P("x+x")).kind == .symbolic)173 #expect(Symbolic.simplify(P("1/0")).kind == .unsupported)174 #expect(Symbolic.simplify(P("tan(pi/2)")).kind == .unsupported)175 #expect(Symbolic.simplify(P("x+x")).verification.isVerified)176 }177}178179@Suite struct Calculus {180 @Test func canonicalDerivatives() {181 #expect(diff("x^2") == "2x")182 #expect(diff("sin(x)") == "cos(x)")183 #expect(diff("cos(x)") == "−sin(x)")184 #expect(diff("e^x") == "exp(x)")185 #expect(diff("ln(x)") == "1/x")186 #expect(diff("x^3", order: 2) == "6x")187 #expect(diff("5") == "0")188 #expect(diff("x^2*y^3", "y") == "3x² · y²")189 #expect(diff("abs(x)") == "sign(x)")190 #expect(diff("sqrt(x)") == "1/(2√(x))")191 #expect(Symbolic.differentiate(P("x^2*y"), variables: ["x", "y"]).text == "2x")192 #expect(Symbolic.gradient(P("x^2*y + sin(y)"), variables: ["x", "y"]).text == "[2x · y, x² + cos(y)]")193 }194 @Test func derivativeExplanationNamesTheRealRules() {195 let r = Symbolic.differentiate(P("x^2*sin(x)"), variable: "x")196 let text = r.explanation.plainText197 #expect(text.contains("Product rule") && text.contains("u = x²") && text.contains("v = sin(x)"))198 #expect(text.contains("Power rule"))199 #expect(Symbolic.differentiate(P("sin(x^2)"), variable: "x").explanation.plainText.contains("Chain rule"))200 #expect(Symbolic.differentiate(P("sin(x)/x"), variable: "x").explanation.plainText.contains("Quotient rule"))201 #expect(Symbolic.differentiate(P("x^x"), variable: "x").explanation.plainText.contains("General power rule"))202 let a = Symbolic.differentiate(P("abs(x)"), variable: "x")203 #expect(a.explanation.assumptions.contains { $0.contains("not differentiable") })204 }205 @Test func unsupportedDerivatives() {206 #expect(Symbolic.differentiate(P("gamma(x)"), variable: "x").kind == .unsupported)207 #expect(Symbolic.differentiate(P("x!"), variable: "x").kind == .unsupported)208 #expect(Symbolic.differentiate(P("x > 1"), variable: "x").kind == .unsupported)209 #expect(Symbolic.differentiate(P("x^2"), variable: "x", order: 25).kind == .unsupported)210 }211 @Test func angleModePolicy() {212 // Symbolic calculus is in radians: trigonometry in DEG / GRAD is refused, everything else still works.213 let degrees = SymbolicOptions(angleMode: .degrees)214 let refused = Symbolic.differentiate(P("sin(x)"), variable: "x", options: degrees)215 #expect(refused.kind == .unsupported && refused.note.contains("radians") && refused.expression == nil)216 #expect(Symbolic.integrate(P("cos(x)"), variable: "x", options: degrees).kind == .unsupported)217 #expect(Symbolic.simplify(P("sin(pi)"), options: SymbolicOptions(angleMode: .gradians)).kind == .unsupported)218 #expect(Symbolic.limit(P("sin(x)/x"), variable: "x", to: .zero, options: degrees).kind == .unsupported)219 #expect(Symbolic.solve(P("sin(x) = 1/2"), for: "x", options: degrees).kind == .unsupported)220 #expect(Symbolic.taylor(P("cos(x)"), variable: "x", order: 4, options: degrees).kind == .unsupported)221 #expect(Symbolic.differentiate(P("x^2*e^x"), variable: "x", options: degrees).text == "x² · exp(x) + 2x · exp(x)")222 }223 @Test func canonicalIntegrals() {224 #expect(integ("x^2") == "x³/3")225 #expect(integ("1/x") == "ln(|x|)")226 #expect(integ("cos(x)") == "sin(x)")227 #expect(integ("e^x") == "exp(x)")228 #expect(integ("1/(x^2+1)") == "atan(x)")229 #expect(integ("1/sqrt(1-x^2)") == "asin(x)")230 #expect(integ("sec(x)^2") == "tan(x)")231 #expect(integ("2x*cos(x^2)") == "sin(x²)")232 let r = Symbolic.integrate(P("x^2"), variable: "x")233 #expect(r.text == "x³/3 + C")234 #expect(r.expression == P("x^3/3")) // "+ C" is presentation only235 }236 @Test func integrationExplanations() {237 #expect(Symbolic.integrate(P("x*ln(x)"), variable: "x").explanation.plainText.contains("Integration by parts"))238 #expect(Symbolic.integrate(P("x^2*e^x"), variable: "x").explanation.plainText.contains("tabular"))239 #expect(Symbolic.integrate(P("2x*cos(x^2)"), variable: "x").explanation.plainText.contains("Substitution"))240 #expect(Symbolic.integrate(P("1/(x*(x+1))"), variable: "x").explanation.plainText.contains("Partial fractions"))241 #expect(Symbolic.integrate(P("sin(x)^2"), variable: "x").explanation.plainText.contains("power-reduction"))242 #expect(Symbolic.integrate(P("3x^2+1"), variable: "x").explanation.plainText.contains("Linearity"))243 }244 @Test func integralsWithoutClosedFormAreRefusedAndFallBackNumerically() {245 for (f, a, b, expected) in [("e^(-x^2)", "0", "1", 0.7468241328124271), ("sin(x)/x", "1", "2", 0.6593299064355118), ("x^x", "1", "2", 2.050446234534731),246 ("1/(x^4+1)", "0", "1", 0.8669729873399110), ("cos(x^2)", "0", "1", 0.9045242379002721), ("1/ln(x)", "2", "3", 1.118424814549702)] {247 let indefinite = Symbolic.integrate(P(f), variable: "x")248 #expect(indefinite.kind == .unsupported, "∫ \(f) should be unsupported, got \(indefinite.text)")249 #expect(indefinite.expression == nil && indefinite.values.isEmpty)250 #expect(indefinite.note.contains("No closed form found"))251 let definite = Symbolic.integrate(P(f), variable: "x", from: P(a), to: P(b))252 #expect(definite.kind == .numerical, "\(f): \(definite.kind) \(definite.note)")253 #expect(definite.expression == nil) // never presented as an exact result254 #expect(close(definite.doubleValue ?? .nan, expected, 1e-10), "\(f): \(definite.doubleValue ?? .nan)")255 #expect((definite.errorEstimate ?? 1) < 1e-8)256 #expect(definite.verification.checks.contains { $0.kind == .convergence })257 }258 }259 @Test func definiteIntegralsRespectDiscontinuities() {260 let pole = Symbolic.integrate(P("1/x"), variable: "x", from: P("-1"), to: P("1"))261 #expect(pole.kind == .unsupported && pole.note.contains("singularity"))262 #expect(Symbolic.integrate(P("1/x^2"), variable: "x", from: P("-1"), to: P("1")).kind == .unsupported) // F(1) − F(−1) = −2 would be wrong263 #expect(Symbolic.integrate(P("tan(x)"), variable: "x", from: P("0"), to: P("2")).kind == .unsupported)264 #expect(Symbolic.integrate(P("sqrt(x)"), variable: "x", from: P("-1"), to: P("1")).kind == .unsupported)265 let jump = Symbolic.integrate(P("floor(x)"), variable: "x", from: P("0"), to: P("3"))266 #expect(jump.kind == .numerical && close(jump.doubleValue ?? .nan, 3, 1e-9))267 let exact = Symbolic.integrate(P("sin(x)"), variable: "x", from: P("0"), to: P("pi"))268 #expect(exact.kind == .exact && exact.text == "2")269 #expect(exact.verification.checks.contains { $0.name == "Numerical quadrature" && $0.status == .passed })270 #expect(Symbolic.integrate(P("1/(1+x^2)"), variable: "x", from: P("-inf"), to: P("inf")).text == "π")271 #expect(Symbolic.integrate(P("ln(x)"), variable: "x", from: P("0"), to: P("1")).text == "−1")272 let divergent = Symbolic.integrate(P("1/x"), variable: "x", from: P("1"), to: P("inf"))273 #expect(divergent.note.contains("diverges"))274 let symbolic = Symbolic.integrate(P("a*x"), variable: "x", from: P("0"), to: P("b"))275 #expect(symbolic.kind == .symbolic && symbolic.verification.warnings.count == 1)276 #expect(Symbolic.integrate(P("x"), variable: "x", from: P("2"), to: P("2")).text == "0")277 #expect(Symbolic.integrate(P("x"), variable: "x", from: P("1"), to: P("0")).text == "−1/2")278 }279 @Test func limits() {280 let l = Symbolic.limit(P("sin(x)/x"), variable: "x", to: .zero)281 #expect(l.kind == .exact && l.text == "1" && l.explanation.plainText.contains("L'Hôpital"))282 #expect(Symbolic.limit(P("(1+1/x)^x"), variable: "x", to: P("inf")).text == "e")283 #expect(Symbolic.limit(P("(3x^2+1)/(2x^2-x)"), variable: "x", to: P("inf")).explanation.plainText.contains("Degree comparison"))284 let none = Symbolic.limit(P("1/x"), variable: "x", to: .zero)285 #expect(none.behavior == .doesNotExist && none.leftText == "−∞" && none.rightText == "∞" && none.expression == nil)286 #expect(Symbolic.limit(P("1/x"), variable: "x", to: .zero, direction: .right).behavior == .positiveInfinity)287 #expect(Symbolic.limit(P("1/x"), variable: "x", to: .zero, direction: .left).behavior == .negativeInfinity)288 #expect(Symbolic.limit(P("abs(x)/x"), variable: "x", to: .zero).behavior == .doesNotExist)289 #expect(Symbolic.limit(P("floor(x)"), variable: "x", to: P("2")).behavior == .doesNotExist)290 #expect(Symbolic.limit(P("floor(x)"), variable: "x", to: P("2"), direction: .left).text == "1")291 #expect(Symbolic.limit(P("sin(1/x)"), variable: "x", to: .zero).behavior == .doesNotExist)292 #expect(Symbolic.limit(P("x*sin(1/x)"), variable: "x", to: .zero).explanation.plainText.contains("Squeeze"))293 let numerical = Symbolic.limit(P("sqrt(x^2+x)-x"), variable: "x", to: P("inf"))294 #expect(numerical.kind == .numerical && numerical.expression == nil && abs((numerical.value ?? 0) - 0.5) < 1e-6 && numerical.errorEstimate != nil)295 let oneSided = Symbolic.limit(P("sqrt(x)"), variable: "x", to: .zero)296 #expect(oneSided.text == "0" && oneSided.note.contains("from the right"))297 #expect(Symbolic.limit(P("ln(x)"), variable: "x", to: P("-1")).kind == .unsupported)298 #expect(Symbolic.limit(P("a*x^2"), variable: "x", to: P("b")).text == "a · b²")299 }300 @Test func series() {301 #expect(Symbolic.taylor(P("sin(x)"), variable: "x", order: 5).text == "x − x³/6 + x⁵/120 + O(x⁶)")302 #expect(Symbolic.taylor(P("e^x"), variable: "x", order: 3).text == "1 + x + x²/2 + x³/6 + O(x⁴)")303 #expect(Symbolic.taylor(P("ln(x)"), variable: "x", around: P("1"), order: 3).text == "x − 1 − (x − 1)²/2 + (x − 1)³/3 + O((x − 1)⁴)")304 let s = Symbolic.taylor(P("cos(x)"), variable: "x", order: 4)305 #expect(s.order == 4 && s.coefficients.count == 5 && s.coefficients[2] == P("-1/2").self || pretty(s.coefficients[2]) == "−1/2")306 #expect(s.verification.isVerified)307 #expect(Symbolic.taylor(P("ln(x)"), variable: "x", order: 3).kind == .unsupported)308 #expect(Symbolic.taylor(P("abs(x)"), variable: "x", order: 40).kind == .unsupported)309 #expect(Symbolic.sum(P("k"), index: "k", from: P("1"), to: P("n")).text == "n · (n + 1)/2")310 #expect(Symbolic.sum(P("k^2"), index: "k", from: P("1"), to: P("10")).text == "385")311 #expect(Symbolic.sum(P("k^2"), index: "k", from: P("1"), to: P("1000000")).text == "333333833333500000")312 let geometric = Symbolic.sum(P("(1/2)^k"), index: "k", from: P("0"), to: P("inf"))313 #expect(geometric.kind == .exact && geometric.text == "2" && geometric.note.contains("|r|"))314 #expect(Symbolic.sum(P("2^k"), index: "k", from: P("0"), to: P("inf")).note.contains("diverges"))315 #expect(Symbolic.sum(P("r^k"), index: "k", from: P("0"), to: P("inf")).explanation.assumptions.contains { $0.contains("< 1") })316 #expect(Symbolic.sum(P("1/k^2"), index: "k", from: P("1"), to: P("inf")).kind == .unsupported)317 #expect(Symbolic.sum(P("1/k"), index: "k", from: P("1"), to: P("4")).text == "25/12")318 }319}320321@Suite struct Solving {322 func roots(_ s: String) -> [String] { Symbolic.solve(P(s), for: "x").solutions.map(\.text) }323324 @Test func exactEquations() {325 #expect(roots("2x+3=7") == ["2"])326 #expect(roots("x^2-5x+6=0") == ["2", "3"])327 #expect(roots("x^2=2") == ["−√(2)", "√(2)"])328 #expect(roots("x^2+x-1=0") == ["−√(5)/2 − 1/2", "√(5)/2 − 1/2"])329 #expect(roots("e^(2x)-3e^x+2=0") == ["0", "ln(2)"])330 #expect(roots("x^4-5x^2+4=0") == ["−2", "−1", "1", "2"])331 #expect(roots("ln(x)=2") == ["exp(2)"])332 #expect(roots("2^x=8") == ["3"])333 #expect(roots("abs(x-2)=3") == ["−1", "5"])334 #expect(roots("1/(x-1)=2") == ["3/2"])335 #expect(roots("x-3sqrt(x)+2=0") == ["1", "4"])336 #expect(roots("x^4-10x^2+1=0").count == 4)337 let quadratic = Symbolic.solve(P("x^2-5x+6=0"), for: "x")338 #expect(quadratic.kind == .exact && quadratic.explanation.plainText.contains("Δ = 1") && quadratic.explanation.plainText.contains("Discriminant"))339 }340 @Test func doubleRootsComplexRootsAndNoSolution() {341 let double = Symbolic.solve(P("x^2-2x+1=0"), for: "x")342 #expect(double.solutions.count == 1 && double.solutions[0].multiplicity == 2 && double.solutions[0].text == "1")343 let complex = Symbolic.solve(P("x^2+1=0"), for: "x")344 #expect(complex.realSolutions.isEmpty && complex.solutions.map(\.text) == ["−i", "i"] && complex.note.contains("No real solution"))345 let pair = Symbolic.solve(P("x^2+2x+5=0"), for: "x")346 #expect(pair.solutions.map(\.text) == ["−1 − 2i", "−1 + 2i"])347 #expect(pair.solutions.allSatisfy { $0.kind == .exact && $0.imaginary != 0 && abs($0.real + 1) < 1e-15 })348 let cube = Symbolic.solve(P("x^3=8"), for: "x")349 #expect(cube.realSolutions.map(\.text) == ["2"] && cube.solutions.count == 3)350 let none = Symbolic.solve(P("e^x=-1"), for: "x")351 #expect(none.solutions.isEmpty && none.note.contains("No solution") && !none.rejected.isEmpty)352 #expect(Symbolic.solve(P("sin(x)=2"), for: "x").solutions.isEmpty)353 #expect(Symbolic.solve(P("x=x"), for: "x").isIdentity)354 #expect(Symbolic.solve(P("3=4"), for: "x").note.contains("no solution"))355 }356 @Test func extraneousRootsAreRejected() {357 let r = Symbolic.solve(P("sqrt(x+1)=x-1"), for: "x")358 #expect(r.solutions.map(\.text) == ["3"])359 #expect(r.rejected.count == 1 && r.rejected[0].contains("x = 0") && r.rejected[0].contains("extraneous"))360 #expect(r.explanation.plainText.contains("Extraneous root rejected"))361 let never = Symbolic.solve(P("sqrt(x)=-1"), for: "x")362 #expect(never.solutions.isEmpty && never.rejected.count == 1)363 let removed = Symbolic.solve(P("(x^2-1)/(x-1)=0"), for: "x")364 #expect(removed.solutions.map(\.text) == ["−1"]) // x = 1 is not in the domain365 let logs = Symbolic.solve(P("ln(x)+ln(x-3)=ln(4)"), for: "x", in: 0.5...20)366 #expect(logs.realSolutions.count == 1 && abs(logs.realSolutions[0].real - 4) < 1e-9)367 for s in r.solutions + removed.solutions { #expect(s.residual <= 1e-9) }368 }369 @Test func trigonometricEquationsReturnPrincipalSolutionsWithTheGeneralSolutionNoted() {370 let r = Symbolic.solve(P("sin(x)=1/2"), for: "x")371 #expect(r.solutions.map(\.text) == ["π/6", "5π/6"] && r.note.contains("2πk"))372 #expect(Symbolic.solve(P("tan(x)=1"), for: "x").solutions.map(\.text) == ["π/4"])373 #expect(Symbolic.solve(P("cos(2x)=0"), for: "x").solutions.map(\.text) == ["−π/4", "π/4"])374 }375 @Test func symbolicParameters() {376 let linear = Symbolic.solve(P("a*x+b=0"), for: "x")377 #expect(linear.kind == .symbolic && linear.solutions.map(\.text) == ["−b/a"])378 let quadratic = Symbolic.solve(P("a*x^2+b*x+c=0"), for: "x")379 #expect(quadratic.solutions.count == 2 && quadratic.explanation.plainText.contains("Quadratic formula"))380 #expect(Symbolic.solve(P("a*sin(x)+x=1"), for: "x").kind == .unsupported)381 }382 @Test func numericalFallbackIsLabelled() {383 let r = Symbolic.solve(P("cos(x)=x"), for: "x")384 #expect(r.kind == .numerical && r.solutions.count == 1 && r.solutions[0].expression == nil)385 #expect(abs(r.solutions[0].real - 0.7390851332151607) < 1e-12 && r.solutions[0].residual < 1e-12)386 #expect(r.note.contains("Numerical"))387 let many = Symbolic.solve(P("sin(x)=x/5"), for: "x", in: -6...6)388 #expect(many.solutions.count == 3 && many.solutions.allSatisfy { $0.kind == .numerical })389 let none = Symbolic.solve(P("e^x+x^2=-1"), for: "x")390 #expect(none.kind == .numerical && none.solutions.isEmpty && none.note.contains("No real root"))391 let quintic = Symbolic.solve(P("x^5-x-1=0"), for: "x")392 #expect(quintic.kind == .numerical && quintic.realSolutions.count == 1 && quintic.solutions.count == 5)393 #expect(Symbolic.solve(P("x > 2"), for: "x").kind == .unsupported)394 }395 @Test func polynomialRootsAPI() {396 let r = Symbolic.polynomialRoots(Polynomial(integers: [-6, 11, -6, 1]))397 #expect(r.kind == .exact && r.roots.map(\.text) == ["1", "2", "3"] && r.verification.isVerified)398 let m = Symbolic.polynomialRoots(Polynomial(integers: [1, -1]).power(3) * Polynomial(integers: [1, 0, 1]))399 #expect(m.roots.first { $0.isReal }?.multiplicity == 3 && m.roots.filter { !$0.isReal }.count == 2)400 let cubic = Symbolic.polynomialRoots(Polynomial(integers: [1, -1, 0, 1]))401 #expect(cubic.kind == .numerical && cubic.roots.allSatisfy { $0.expression == nil && $0.kind == .numerical && $0.residual < 1e-12 })402 #expect(Symbolic.polynomialRoots(Polynomial(integers: [3])).kind == .unsupported)403 }404}405406@Suite struct PolynomialAlgebra {407 @Test func arithmeticIdentities() throws {408 var rng = SeededGenerator(seed: 99)409 func random(_ degree: Int) -> Polynomial {410 Polynomial((0...degree).map { _ in BigRational(BigInt(Int(rng.uniform(-9, 10))), BigInt(Int(rng.uniform(1, 6)))) })411 }412 for round in 0..<60 {413 let a = random(Int(rng.uniform(1, 9))), b = random(Int(rng.uniform(1, 5)))414 guard !b.isZero else { continue }415 let (q, r) = a.dividing(by: b)416 #expect(q * b + r == a)417 #expect(r.degree < b.degree)418 let g = Polynomial.gcd(a * b, b * b)419 #expect(g.degree >= b.degree && (b * b).dividing(by: g).remainder.isZero && (a * b).dividing(by: g).remainder.isZero)420 #expect((a * b).derivative == a.derivative * b + a * b.derivative)421 #expect(a.antiderivative.derivative == a)422 let x = BigRational(BigInt(Int(rng.uniform(-5, 6))), 3)423 #expect((a * b).evaluate(x) == a.evaluate(x) * b.evaluate(x))424 #expect(a.composed(with: b).evaluate(x) == a.evaluate(b.evaluate(x)))425 #expect(a - a == .zero && a + .zero == a && a * .one == a)426 // factor(expand(p)) round trip427 if round < 12 { #expect((a * b).factorized().product == a * b) }428 }429 }430 @Test func conversion() throws {431 let p = try #require(Polynomial(P("(x-1)^2*(2x+3) + 1/2"), variable: "x"))432 #expect(p.coefficients == [BigRational(7, 2), BigRational(-4), BigRational(-1), BigRational(2)])433 #expect(p.degree == 3 && p.description == "2x³ − x² − 4x + 7/2")434 #expect(p.evaluate(BigRational(1, 2)) == BigRational(3, 2))435 #expect(Polynomial(P("sin(x)"), variable: "x") == nil)436 #expect(Polynomial(P("x*y"), variable: "x") == nil)437 #expect(Polynomial(P("1/x"), variable: "x") == nil)438 #expect(Polynomial(P("x^1000"), variable: "x") == nil) // above the degree bound439 let decomposition = Polynomial(integers: [-6, 4]).primitiveDecomposition440 #expect(decomposition.content == BigRational(2) && decomposition.primitive == Polynomial(integers: [-3, 2]))441 #expect(Polynomial.gcd(Polynomial(integers: [-1, 0, 1]), Polynomial(integers: [1, 2, 1])) == Polynomial(integers: [1, 1]))442 }443 @Test func factorisationReportsMultiplicitiesAndHonestIrreducibility() {444 let fz = (Polynomial(integers: [-1, 1]).power(3) * Polynomial(integers: [2, 1]).power(2) * Polynomial(integers: [1, 0, 1])).scaled(by: BigRational(5, 3)).factorized()445 #expect(fz.content == BigRational(5, 3))446 #expect(fz.factors.map(\.multiplicity).sorted() == [1, 2, 3] && fz.isComplete)447 // degree 10 irreducible: cubic and quartic factors are searched; beyond the bound the factor is not claimed irreducible448 let big = Polynomial(integers: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).factorized()449 #expect(big.product == Polynomial(integers: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))450 for f in big.factors where f.polynomial.degree >= 10 { #expect(!f.isProvenIrreducible) }451 }452}453454@Suite struct BoundsAndPerformance {455 @Test func oversizedInputIsRefusedCleanly() {456 var e = Expr.variable("x")457 for _ in 0..<1000 { e = .call("sin", [e]) } // nesting far above the limit458 #expect(Symbolic.simplify(e).kind == .unsupported)459 #expect(Symbolic.differentiate(e, variable: "x").kind == .unsupported)460 #expect(Polynomial(e, variable: "x") == nil)461 let wide = Expr.call("max", (0..<30_000).map { Expr.binary(.multiply, .int($0), .variable("x")) }) // more nodes than the limit462 #expect(Symbolic.simplify(wide).note.contains("too large"))463 var chain = Expr.variable("x")464 for k in 1...3000 { chain = .binary(.add, chain, .binary(.multiply, .int(k), .variable("x"))) } // long flat sums are fine465 #expect(Symbolic.simplify(chain).text == "4501501x")466 }467 @Test func simplifyingA200NodeExpressionIsFast() {468 var terms: [String] = []469 for k in 1...22 { terms.append("\(k)*x^\(k % 5)*sin(x)^2 + (x+\(k))*(y-\(k))/\(k + 1)") }470 let e = P(terms.joined(separator: " + "))471 #expect(Guard.measure(e).nodes >= 200)472 var best = Double.infinity473 for _ in 0..<5 {474 let start = ContinuousClock.now475 _ = Node.from(e).expr476 let d = ContinuousClock.now - start477 best = min(best, Double(d.components.attoseconds) / 1e18 + Double(d.components.seconds))478 }479 #expect(best < 0.05, "canonical simplification took \(best * 1000) ms")480 let full = ContinuousClock.now481 #expect(Symbolic.simplify(e).isSuccess)482 let elapsed = ContinuousClock.now - full483 #expect(elapsed < .milliseconds(50), "Symbolic.simplify took \(elapsed)")484 }485 @Test func hardProblemsTerminate() {486 let start = ContinuousClock.now487 #expect(Symbolic.integrate(P("sin(x^3)*e^(cos(x))/(1+x^7)"), variable: "x").kind == .unsupported)488 #expect(Symbolic.integrate(P("sqrt(1+x^4)"), variable: "x").kind == .unsupported)489 #expect(Symbolic.limit(P("sin(x)^cos(1/x)"), variable: "x", to: .zero).kind != .exact)490 #expect(Symbolic.solve(P("x^x = 2"), for: "x").kind == .numerical)491 _ = Symbolic.differentiate(P("x^x^x"), variable: "x", order: 6)492 _ = Symbolic.taylor(P("tan(sin(x))*e^x"), variable: "x", order: 8)493 #expect(ContinuousClock.now - start < .seconds(20))494 }495}496