Sources/OrgCore/Compute/CalcSymbolic.swift
694 lines · 33955 bytes
1import Foundation
2
3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and
4/// quotients by zero. This ports `math-add`, `math-mul`, `math-div`, `math-pow` and `math-neg`
5/// with their `-symb-fancy` helpers from calc.el and calc-arith.el, as `calc-eval` runs them
6/// with `calc-simplify-mode` nil, and Calc's flat formula printer from calccomp.el. Anything
7/// those functions would decide from declarations, units, matrices or intervals throws
8/// `Calc.Unsupported`.
9extension Calc {
10 /// A formula, as Calc's Lisp form: a number, a variable, or an operator or function with
11 /// its arguments (`+ - * / ^ neg`, or a function name).
12 public indirect enum Term: Equatable, Sendable {
13 case number(Value)
14 case variable(String)
15 case op(String, [Term])
16 }
17
18 /// `math-reject-arg`: the operation stays unevaluated.
19 struct Rejected: Error {}
20
21 /// `calc-symbolic-mode`.
22 @TaskLocal static var symbolicMode = false
23
24 /// `calc-prefer-frac`, for the division the arithmetic does.
25 @TaskLocal static var fractions = false
26
27 /// Variables Calc gives a value or a declaration, which would change the arithmetic.
28 static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
29 "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
30 "NegateRules"]
31
32 /// The special constants and infinities, whose sign or type Calc knows.
33 static let constants: Set<String> = ["pi", "e", "phi", "gamma", "i", "inf", "uinf", "nan"]
34
35 static func term(_ v: Value) throws -> Term {
36 switch v {
37 case .symbolic(let t): return t
38 case .nan: return .variable("nan")
39 case .int, .float, .frac: return .number(v)
40 case .vector, .date: throw Unsupported("symbolic arithmetic")
41 }
42 }
43
44 static func value(_ t: Term) -> Value {
45 switch t {
46 case .number(let v): return v
47 case .variable("nan"): return .nan
48 default: return .symbolic(t)
49 }
50 }
51
52 enum Symbolic {
53 static let inf = Term.variable("inf")
54 static let uinf = Term.variable("uinf")
55 static let nan = Term.variable("nan")
56
57 // MARK: Predicates
58
59 static func number(_ t: Term) -> Value? {
60 if case .number(let v) = t { return v }
61 return nil
62 }
63
64 static func head(_ t: Term) -> String? {
65 if case .op(let f, _) = t { return f }
66 return nil
67 }
68
69 /// `(nth n a)`, from 1.
70 static func arg(_ t: Term, _ n: Int) -> Term {
71 guard case .op(_, let args) = t, n - 1 < args.count else { return .number(.int(0)) }
72 return args[n - 1]
73 }
74
75 static func objectp(_ t: Term) -> Bool { number(t) != nil }
76 static func zerop(_ t: Term) -> Bool { number(t).map(isZero) ?? false }
77 static func floatp(_ t: Term) -> Bool {
78 if case .number(.float) = t { return true }
79 return false
80 }
81 static func ratp(_ t: Term) -> Bool { number(t).map { rational($0) != nil } ?? false }
82 static func integerp(_ t: Term) -> Bool {
83 if case .number(.int) = t { return true }
84 return false
85 }
86
87 /// `math-negp`.
88 static func negp(_ t: Term) -> Bool {
89 if let v = number(t) { return (try? sign(v)) == -1 }
90 return t == .op("neg", [inf])
91 }
92
93 /// `math-posp`.
94 static func posp(_ t: Term) -> Bool {
95 if let v = number(t) { return (try? sign(v)) == 1 }
96 return t == inf
97 }
98
99 /// `Math-equal-int`.
100 static func equalInt(_ t: Term, _ n: Int) -> Bool {
101 t == .number(.int(n)) || t == .number(.float(n, 0))
102 }
103
104 /// `math-looks-negp`; `loose` false is the `Math-looks-negp` macro, which doesn't
105 /// look inside a difference.
106 static func looksNeg(_ t: Term, loose: Bool = true) -> Bool {
107 if negp(t) { return true }
108 switch head(t) {
109 case "neg": return true
110 case "*", "/": return looksNeg(arg(t, 1)) || looksNeg(arg(t, 2))
111 case "-": return loose && looksNeg(arg(t, 1))
112 default: return false
113 }
114 }
115
116 /// `math-infinitep`: the infinity a product, quotient or negation is made of.
117 static func infinitep(_ t: Term) -> Term? {
118 var a = t
119 while let f = head(a), ["*", "/", "neg"].contains(f) {
120 a = f != "*" || infinitep(arg(a, 1)) != nil ? arg(a, 1) : arg(a, 2)
121 }
122 return [inf, uinf, nan].contains(a) ? a : nil
123 }
124
125 static func containsConstant(_ t: Term) -> Bool {
126 switch t {
127 case .number: false
128 case .variable(let name): constants.contains(name)
129 case .op(_, let args): args.contains(where: containsConstant)
130 }
131 }
132
133 /// `math-possible-signs`: the bits 1 negative, 2 zero, 4 positive and 8 not real,
134 /// relative to `origin`. Nothing is declared, so a variable may be anything.
135 static func signs(_ a: Term, _ origin: Term? = nil) throws -> Int {
136 func negSigns(_ s: Int) -> Int {
137 s >= 8 ? 8 + negSigns(s - 8) : (s & 1 != 0 ? 4 : 0) | (s & 2) | (s & 4 != 0 ? 1 : 0)
138 }
139 if objectp(a) {
140 let x = try origin.map { try sub(a, $0) } ?? a
141 return posp(x) ? 4 : negp(x) ? 1 : 2
142 }
143 let (a1, a2) = (arg(a, 1), arg(a, 2))
144 let f = head(a)
145 if f == "+" || f == "-" {
146 if objectp(a1) {
147 if f == "-" { return negSigns(try signs(a2, try origin.map { try add($0, a1) } ?? a1)) }
148 return try signs(a2, try origin.map { try sub($0, a1) } ?? (try neg(a1)))
149 }
150 if objectp(a2) {
151 let org = f == "-" ? a2 : try neg(a2)
152 return try signs(a1, try origin.map { try add($0, org) } ?? org)
153 }
154 let s1 = try signs(a1, origin)
155 var s2 = try signs(a2)
156 if f == "-" { s2 = negSigns(s2) }
157 if s1 == s2 { return s1 }
158 if s1 == 2 { return s2 }
159 if s2 == 2 { return s1 }
160 if s1 >= 8 || s2 >= 8 { return 15 }
161 if (s1, s2) == (4, 6) || (s1, s2) == (6, 4) { return 4 }
162 if (s1, s2) == (1, 3) || (s1, s2) == (3, 1) { return 1 }
163 return 7
164 }
165 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
166 let origin = origin.flatMap { zerop($0) ? nil : $0 }
167 let zero = Term.number(.int(0))
168 if f == "*" || (f == "/" && origin != nil), objectp(a1) {
169 let s = f == "*"
170 ? (zerop(a1) ? try signs(zero, origin) : try signs(a2, try div(origin ?? zero, a1)))
171 : negSigns(try signs(a2, try div(a1, origin!)))
172 return negp(a1) ? negSigns(s) : s
173 }
174 if f == "*" || f == "/", objectp(a2) {
175 let s = try signs(a1, f == "*" ? try mul(origin ?? zero, a2) : try div(origin ?? zero, a2))
176 return negp(a2) ? negSigns(s) : s
177 }
178 let sign: Int
179 switch a {
180 case .op("*", _), .op("/", _):
181 let (s1, s2) = (try signs(a1), try signs(a2))
182 if s1 >= 8 || s2 >= 8 || (f == "/" && [2, 3, 6, 7].contains(s2)) {
183 sign = 15
184 } else {
185 sign = (s1 & 4 != 0 ? s2 : 0) | (s1 & 2) | (s1 & 1 != 0 ? negSigns(s2) : 0)
186 }
187 case .op("^", _):
188 let (s1, s2) = (try signs(a1), try signs(a2))
189 if s1 >= 8 || s2 >= 8 {
190 sign = 15
191 } else if s1 == 4 {
192 sign = 4
193 } else if s1 == 2 {
194 sign = s2 == 4 ? 2 : 15
195 } else if s2 == 2 {
196 sign = [1, 5].contains(s1) ? 2 : 15
197 } else if case .number(.int(let n)) = a2 {
198 sign = n % 2 == 0 ? ([3, 6, 7].contains(s1) ? 6 : 4) : s1
199 } else if s1 == 6 {
200 sign = s2 == 4 ? 6 : 15
201 } else {
202 sign = 7
203 }
204 case .variable(let name):
205 switch name {
206 case "pi", "e":
207 guard origin == nil else { throw Unsupported("symbolic arithmetic") }
208 return 4
209 case "inf": return 4
210 case "uinf": return 13
211 case "i": return 8
212 default: return 15
213 }
214 default: throw Unsupported("function \(f ?? "")")
215 }
216 guard let origin else { return sign }
217 if posp(origin) { return (sign & 8) + ([1, 2, 3, 8, 9, 10, 11].contains(sign) ? 1 : 7) }
218 return (sign & 8) + ([2, 4, 6, 8, 10, 12, 14].contains(sign) ? 4 : 7)
219 }
220
221 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
222
223 /// `math-known-num-integerp`.
224 static func knownNumInteger(_ t: Term) throws -> Bool {
225 if let v = number(t) { return isWhole(v) }
226 guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") }
227 return try possibleTypes(t, num: true) <= 3
228 }
229
230 /// `math-possible-types`: the bits 1 integer, 2 integer-valued float, 4 fraction and
231 /// 8 float, with `num` merging 1 and 2 and merging 4 and 8. Nothing is declared, so a
232 /// variable may be anything (63). Results above 15 are all 63 here: only whether a
233 /// result is at most 3 is used, and no larger operand can make it so.
234 static func possibleTypes(_ a: Term, num: Bool = false) throws -> Int {
235 func merge(_ t1: Int, _ t2: Int, _ mask: Int) -> Int {
236 if num { return mask * 3 }
237 return (t1 & 5 > 0 && t2 & 5 > 0 ? mask : 0) | ((t1 | t2) & 10 > 0 ? mask * 2 : 0)
238 }
239 switch a {
240 case .number(.int): return num ? 3 : 1
241 case .number(.float(_, let e)) where e >= 0: return num ? 3 : 2
242 case .number(.frac): return num ? 12 : 4
243 case .number(.float): return num ? 12 : 8
244 case .number: throw Unsupported("symbolic arithmetic")
245 case .variable: return 63
246 case .op("neg", let args): return try possibleTypes(args[0])
247 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^"].contains(f):
248 let (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
249 let t12 = t1 | t2
250 if f == "^" {
251 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
252 return try knownNonneg(args[0]) && signs(args[1]) == 4 ? 15 : 63
253 }
254 let mask = (t1 & 3 > 0 ? 1 : 0) | (t1 & 4) | (t1 & 12 > 0 ? 5 : 0)
255 return merge(t1, t2, mask)
256 }
257 guard t12 < 16 else { return 63 }
258 if f == "/" {
259 if t12 & 10 > 0 { return 10 }
260 return t1 == 4 || t2 == 4 || fractions ? 5 : 15
261 }
262 let mask = t12 <= 3 ? 1
263 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && f != "*" ? 4 : 5
264 return merge(t1, t2, mask)
265 default: throw Unsupported("function \(head(a) ?? "")")
266 }
267 }
268
269 // MARK: Arithmetic
270
271 /// `math-normalize`: the operations applied again from the leaves, floats rounded
272 /// to the precision.
273 static func normalize(_ t: Term) throws -> Term {
274 switch t {
275 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
276 case .number, .variable: return t
277 case .op(let f, let args):
278 let args = try args.map(normalize)
279 do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
280 }
281 }
282
283 static func apply(_ f: String, _ args: [Term]) throws -> Term {
284 switch (f, args.count) {
285 case ("+", 2): return try add(args[0], args[1])
286 case ("-", 2): return try sub(args[0], args[1])
287 case ("*", 2): return try mul(args[0], args[1])
288 case ("/", 2): return try div(args[0], args[1])
289 case ("^", 2): return try pow(args[0], args[1])
290 case ("neg", 1): return try neg(args[0])
291 default: throw Unsupported("function \(f)")
292 }
293 }
294
295 static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? {
296 guard let x = number(a), let y = number(b) else { return nil }
297 return try term(try op(x, y))
298 }
299
300 /// `math-float` of a rational number.
301 static func float(_ t: Term) throws -> Term {
302 guard let v = number(t) else { return t }
303 return .number(try Calc.float(v))
304 }
305
306 /// `math-neg`.
307 static func neg(_ a: Term) throws -> Term {
308 if let v = number(a) { return .number(try negate(v)) }
309 func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" }
310 let (a1, a2) = (arg(a, 1), arg(a, 2))
311 switch head(a) {
312 case "+": return try sub(try neg(a1), a2)
313 case "-": return try sub(a2, a1)
314 case "*", "/":
315 let f = head(a)!
316 if okayNeg(a1) { return .op(f, [try neg(a1), a2]) }
317 if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) }
318 if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) }
319 if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) }
320 case "neg": return a1
321 default: if a == uinf || a == nan { return a }
322 }
323 return .op("neg", [a])
324 }
325
326 /// `math-add`.
327 static func add(_ a: Term, _ b: Term) throws -> Term {
328 if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum }
329 if zerop(a) { return b }
330 if zerop(b) { return a }
331 return try addFancy(a, b)
332 }
333
334 /// `math-sub`.
335 static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) }
336
337 /// `math-add-symb-fancy`.
338 static func addFancy(_ a: Term, _ b: Term) throws -> Term {
339 switch head(b) {
340 case "+": return try add(try add(a, arg(b, 1)), arg(b, 2))
341 case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2))
342 case "neg" where head(arg(b, 1)) == "+":
343 return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2))
344 default: break
345 }
346 if let result = try combineSums(a, b) { return result }
347 if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) }
348 if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) }
349 return .op("+", [a, b])
350 }
351
352 /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms.
353 static func combineSums(_ a: Term, _ b: Term) throws -> Term? {
354 if let infA = infinitep(a) {
355 guard let infB = infinitep(b) else { return a }
356 if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan }
357 let dirA = try infiniteDirection(a, infA)
358 let dirB = try infiniteDirection(b, infB)
359 guard let x = number(dirA), let y = number(dirB) else { return nil }
360 return try compare(x, y) == 0 ? a : nan
361 }
362 if infinitep(b) != nil { return b }
363 if head(a) == "+" {
364 return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
365 }
366 if head(a) == "-" {
367 return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
368 }
369 if objectp(a), objectp(b) { return nil }
370 return try combineSum(a, b, negA: false, negB: false, scalarOkay: false)
371 }
372
373 /// `math-infinite-dir`: the formula with its infinity replaced by 1.
374 static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term {
375 func substitute(_ t: Term) -> Term {
376 if t == infinity { return .number(.int(1)) }
377 if case .op(let f, let args) = t { return .op(f, args.map(substitute)) }
378 return t
379 }
380 return try normalize(substitute(a))
381 }
382
383 /// `math-combine-sum`: two terms that are multiples of the same thing, added.
384 static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? {
385 if scalarOkay, objectp(a), objectp(b) {
386 return try add(negA ? try neg(a) : a, negB ? try neg(b) : b)
387 }
388 /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`.
389 func split(_ t: Term) throws -> (Term?, Term) {
390 switch head(t) {
391 case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2))
392 case "/" where objectp(arg(t, 2)):
393 let d = arg(t, 2)
394 if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) }
395 return (try div(.number(.int(1)), d), arg(t, 1))
396 case "neg": return (.number(.int(-1)), arg(t, 1))
397 default: return (.number(.int(1)), t)
398 }
399 }
400 let (multA, restA) = try split(a)
401 let (multB, restB) = try split(b)
402 guard restA == restB else { return nil }
403 // `math-make-frac` of two such coefficients divides by zero.
404 if multA == nil, multB == nil { throw Rejected() }
405 guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") }
406 if negA { ma = try neg(ma) }
407 if negB { mb = try neg(mb) }
408 return try mul(try add(ma, mb), restA)
409 }
410
411 /// `math-mul`.
412 static func mul(_ a: Term, _ b: Term) throws -> Term {
413 if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
414 if zerop(a) { return try mulZero(a, b) }
415 if zerop(b) { return try mulZero(b, a) }
416 return try mulFancy(a, b)
417 }
418
419 /// `math-mul-zero`, `a` zero and `b` a formula.
420 static func mulZero(_ a: Term, _ b: Term) throws -> Term {
421 if infinitep(b) != nil { return nan }
422 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
423 }
424
425 /// `math-mul-symb-fancy`.
426 static func mulFancy(_ a: Term, _ b: Term) throws -> Term {
427 if equalInt(a, 1) { return b }
428 if equalInt(a, -1) { return try neg(b) }
429 if objectp(b), !objectp(a) { return try mul(b, a) }
430 if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) }
431 if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) }
432 if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) }
433 let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) }
434 if negativePower(a), !negativePower(b) {
435 return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))])))
436 }
437 if negativePower(b), !negativePower(a) {
438 return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
439 }
440 if head(a) == "/" {
441 if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) }
442 return try div(try mul(arg(a, 1), b), arg(a, 2))
443 }
444 if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) }
445 if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) {
446 let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2)))
447 return f == "+" ? try add(x, y) : try sub(x, y)
448 }
449 if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) }
450 if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) }
451 if head(b) == "*" {
452 if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) }
453 } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) {
454 return c
455 }
456 for special in [nan, uinf] {
457 if a == special { return a }
458 if b == special { return b }
459 }
460 if b == inf {
461 switch try signs(a) {
462 case 4: return b
463 case 1: return try neg(b)
464 case 3, 6: throw Unsupported("symbolic arithmetic")
465 default: break
466 }
467 }
468 if a == inf { return try mul(b, a) }
469 return .op("*", [a, b])
470 }
471
472 /// `math-div`.
473 static func div(_ a: Term, _ b: Term) throws -> Term {
474 if zerop(b) {
475 // `math-div-by-zero`.
476 guard let infinity = infinitep(a) else { throw Rejected() }
477 return infinity == nan ? a : uinf
478 }
479 if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient }
480 // `math-div-zero`.
481 if zerop(a) { return b == nan ? b : a }
482 return try divFancy(a, b)
483 }
484
485 /// `math-div-symb-fancy`.
486 static func divFancy(_ a: Term, _ b: Term) throws -> Term {
487 if equalInt(b, 1) { return a }
488 if equalInt(b, -1) { return try neg(a) }
489 if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) {
490 return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
491 }
492 if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) }
493 if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) }
494 if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) }
495 if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) }
496 if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) }
497 if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) {
498 let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b))
499 return f == "+" ? try add(x, y) : try sub(x, y)
500 }
501 if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) }
502 if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) }
503 if head(a) == "*" {
504 if head(b) == "*" {
505 if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) {
506 return try div(try mul(c, arg(a, 2)), arg(b, 2))
507 }
508 } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) {
509 return try mul(c, arg(a, 2))
510 }
511 } else if head(b) == "*" {
512 if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) }
513 } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) {
514 return c
515 }
516 if infinitep(a) != nil {
517 if infinitep(b) != nil { return nan }
518 if a == nan || a == uinf { return a }
519 if a == inf {
520 if posp(b) { return a }
521 if negp(b) { return try neg(a) }
522 if objectp(b) { throw Unsupported("symbolic arithmetic") }
523 }
524 }
525 if infinitep(b) != nil {
526 if b == nan { return b }
527 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
528 }
529 return .op("/", [a, b])
530 }
531
532 /// `math-mul-or-div`.
533 static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term {
534 if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) }
535 return invB ? try div(a, b) : try mul(a, b)
536 }
537
538 /// `math-combine-prod`: two factors that are powers of the same thing, multiplied.
539 static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? {
540 if (invA && zerop(a)) || (invB && zerop(b)) { return nil }
541 if scalarOkay, objectp(a), objectp(b) {
542 let r = try mulOrDiv(a, b, invA: invA, invB: invB)
543 return objectp(r) ? r : nil
544 }
545 if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) }
546 if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) }
547 func split(_ t: Term) throws -> (Term, Term) {
548 var (base, power) = (t, Term.number(.int(1)))
549 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
550 if head(t) == "sqrt" || head(t) == "exp" { throw Unsupported("symbolic arithmetic") }
551 if case .number(.frac(let n, let d)) = base, n < d {
552 (base, power) = (try div(.number(.int(1)), base), try neg(power))
553 }
554 return (base, power)
555 }
556 var (baseA, powA) = try split(a)
557 var (baseB, powB) = try split(b)
558 if invA { powA = try neg(powA) }
559 if invB { powB = try neg(powB) }
560 func isFrac(_ t: Term) -> Bool {
561 if case .number(.frac) = t { return true }
562 return false
563 }
564 if baseA == baseB {
565 var sum = try add(powA, powB)
566 if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) {
567 if looksNeg(sum), ratp(baseA), posp(baseA) {
568 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
569 }
570 if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
571 return try pow(baseA, sum)
572 }
573 }
574 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
575 if powA == .number(.frac(1, 2)) || powA == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
576 return try pow(try mul(baseA, baseB), powA)
577 }
578 return nil
579 }
580
581 /// `math-pow`.
582 static func pow(_ a: Term, _ b: Term) throws -> Term {
583 if b == nan { return b }
584 if zerop(a) {
585 if let y = number(b) {
586 if try sign(y) > 0 { return floatp(b) ? try float(a) : a }
587 return .number(try power(number(a)!, y, fractions: fractions))
588 }
589 // `math-pow-of-zero` with a formula.
590 switch try signs(b) {
591 case 4: return a
592 case 1: return try div(.number(.int(1)), a)
593 default: return infinitep(b) != nil ? nan : .op("^", [a, b])
594 }
595 }
596 if a == .number(.int(1)) || b == .number(.int(1)) { return a }
597 if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a }
598 if zerop(b) {
599 if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) }
600 // `math-pow-zero`.
601 if infinitep(a) != nil { return nan }
602 return floatp(b) ? .number(.float(1, 0)) : .number(.int(1))
603 }
604 if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) }
605 return try powFancy(a, b)
606 }
607
608 /// `math-pow-fancy` with a formula.
609 static func powFancy(_ a: Term, _ b: Term) throws -> Term {
610 let (a1, a2) = (arg(a, 1), arg(a, 2))
611 switch head(a) {
612 case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2):
613 return try mul(try pow(a1, b), try pow(a2, b))
614 case "/" where try knownNumInteger(b) || knownNonneg(a2):
615 return try div(try pow(a1, b), try pow(a2, b))
616 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
617 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
618 case "^" where try knownNumInteger(b) || knownNonneg(a1):
619 return try pow(a1, try mul(a2, b))
620 case "^":
621 // `math-known-evenp` of an exponent with a variable is false.
622 if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y),
623 (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") }
624 default: break
625 }
626 if looksNeg(a), case .number(.int(let n)) = b {
627 let p = try pow(try neg(a), b)
628 return n % 2 == 0 ? p : try neg(p)
629 }
630 if let infinity = infinitep(a) {
631 if infinity == nan { return infinity }
632 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
633 if posp(b) { return a }
634 if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) }
635 if objectp(b) || infinitep(b) != nil { return nan }
636 throw Unsupported("symbolic arithmetic")
637 }
638 if infinitep(b) != nil {
639 guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") }
640 // `calcFunc-abssqr` of a real number is its square.
641 let scale = try multiply(x, x)
642 if scale == .int(1) || scale == .float(1, 0) { return nan }
643 if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) }
644 if try compare(.int(1), x) < 0 { return b }
645 return uinf
646 }
647 return .op("^", [a, b])
648 }
649
650 // MARK: Display
651
652 /// `math-format-value`: `math-compose-expr` in the flat language.
653 static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String {
654 let text = try compose(t, 0, floatFormat)
655 // Past its width of 1000, `calc-eval` breaks the line.
656 guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") }
657 return text
658 }
659
660 /// Left and right precedence, from `math-standard-ops` with
661 /// `calc-multiplication-has-precedence`.
662 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)]
663
664 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
665 switch t {
666 case .number(let v): return try Calc.format(v, floatFormat)
667 case .variable(let name): return name
668 case .op("neg", let args):
669 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
670 return "-" + (try compose(args[0], 197, floatFormat))
671 case .op(let f, let args):
672 guard let (left, right) = operators[f], args.count == 2 else {
673 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
674 }
675 if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" }
676 var lhs = try compose(args[0], left, floatFormat)
677 let rhs = try compose(args[1], right, floatFormat, div: f == "/")
678 if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" }
679 if f == "*", let next = rhs.first {
680 var lastFactor = args[0]
681 while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) }
682 let isVariable = if case .variable = lastFactor { true } else { false }
683 if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") {
684 return lhs + " " + rhs
685 }
686 return lhs + "*" + rhs
687 }
688 if f == "^" { return lhs + "^" + rhs }
689 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
690 return lhs + " " + f + " " + rhs
691 }
692 }
693 }
694}