Sources/OrgCore/Compute/Calc.swift
2130 lines · 104608 bytes
127 symbols in this file
CalcUnsupportedFailureValueFloatFormatModesevaluateextraemacspipiOver2piOver4twoPipiOver180floatisZerosigntruncisWholenearlyEqualdigitspower10scaleRoundingmakeFloatpartsrationalfractiongcdexactdoubleisSymbolicaddalignnegatesubtractisNaNmultiplydivideisIntegerintegerPowerpowerquartercompareabsolutefloorIntsquareRootexactsquareRootRawexpRawlnRawarctanRawarctan2RawarcsinRawsinRawcosRawnearlyZerosinRaw2cosRaw2sinSeriesln2ln10lnRaw2integerRootfloatRootnthRootrootPowerintegerLogroundscaletoFractionevaluategcdgcdchooseisConstantformatformatDateparseDateastronomicalabsolutedaysInMonthdateTimedateValuedayNumberdatePartstoBusinessDaycheckHolidayRangefromBusinessDayzoneOffsetNodeParserskippeekparsetakeorandcomparisonsumquotientproductfactorAfterunarynotpowerNodeprimaryhasCommanumberEvaluatorevalliteralhasNaNhasSymbolbinarytruthmodidivfloorOfcovariancesumdeviationselementsoneintegerclockcallparts
1import Foundation
2
3/// The part of Emacs Calc that table formulas use, with Calc's number semantics: exact
4/// integers, decimal floats rounded to `calc-internal-prec` digits after every operation, and
5/// Calc's display formats. Anything outside this domain throws `Calc.Unsupported`, and the
6/// caller hands the work to Emacs.
7public enum Calc {
8 public struct Unsupported: Error, Equatable, CustomStringConvertible {
9 public let reason: String
10 /// The left-hand side of the table formula that threw, once recalculation knows it.
11 public var formula: String?
12 public var description: String { reason }
13 init(_ reason: String) { self.reason = reason }
14 }
15
16 /// An error Calc reports, which a table shows as `#ERROR`.
17 public struct Failure: Error, Equatable, CustomStringConvertible {
18 public let reason: String
19 /// Where in the expression Calc reports the error.
20 public let position: Int
21 public var description: String { reason }
22 init(_ reason: String, position: Int = 0) { (self.reason, self.position) = (reason, position) }
23 }
24
25 public indirect enum Value: Equatable, Sendable {
26 case int(Int)
27 /// Mantissa and exponent, normalized: at most `precision` digits, no trailing zeros.
28 case float(Int, Int)
29 case vector([Value])
30 /// A date form: the day number, with the time of day as a fraction.
31 case date(Value)
32 case nan
33 /// An exact fraction, reduced, the denominator above 1 (`calc-prefer-frac`).
34 case frac(Int, Int)
35 /// A formula Calc leaves unevaluated, with variables or a quotient by zero.
36 case symbolic(Term)
37 }
38
39 public enum FloatFormat: Equatable, Sendable {
40 case float(Int), fix(Int), sci(Int), eng(Int)
41 }
42
43 public struct Modes: Equatable, Sendable {
44 public var precision = 12
45 public var format = FloatFormat.float(8)
46 public var degrees = true
47 /// `calc-prefer-frac`: dividing integers gives a fraction.
48 public var preferFractions = false
49 /// `calc-symbolic-mode`: functions whose result isn't exact stay unevaluated.
50 public var symbolic = false
51 /// The clock `now()` reads; nil is the system clock.
52 public var now: Date?
53 /// The local time zone, for `now()`, `julian` and `unixtime`.
54 public var timeZone = TimeZone.current
55 public init() {}
56 }
57
58 /// `calc-eval` of `expression`, as the string Calc would return; with `numeric`, as
59 /// `calc-eval` with `num`, a result that isn't a number is an error.
60 public static func evaluate(_ expression: String, modes: Modes = Modes(), numeric: Bool = false) throws -> String {
61 // Mantissas live in an Int, so 18 digits at most.
62 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
63 return try $precision.withValue(modes.precision) {
64 try $fractions.withValue(modes.preferFractions) {
65 try $symbolicMode.withValue(modes.symbolic) { try $nesting.withValue(Nesting()) {
66 var parser = Parser(expression)
67 let tree = try parser.parse()
68 let value = try Evaluator(modes: modes).eval(tree)
69 if numeric {
70 switch value {
71 case .int, .float, .frac: break
72 case .vector where isConstant(value): break
73 default:
74 // Calc explains the first argument a quotient, power or function
75 // rejected along the way, which isn't tracked here.
76 if tree.mayExplain { throw Unsupported("symbolic arithmetic") }
77 throw Failure("Number expected")
78 }
79 }
80 return try format(value, modes.format)
81 } }
82 }
83 }
84 }
85
86 // MARK: - Numbers
87
88 /// `calc-internal-prec`.
89 @TaskLocal static var precision = 12
90
91 /// `math-with-extra-prec`: `body` with `n` more digits, the result rounded back.
92 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value {
93 let v = try $precision.withValue(precision + n, operation: body)
94 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) }
95 if case .date(.float(let m, let e)) = v { return .date(try makeFloat(Int128(m), e)) }
96 if case .symbolic(let t) = v { return value(try Symbolic.normalize(t)) }
97 return v
98 }
99
100 /// `math-use-emacs-fn`: `f` on a double, as Calc does at up to 16 digits. Above that
101 /// Calc uses its own series, which isn't reproduced.
102 static func emacs(_ f: (Double) -> Double, _ x: Value) throws -> Value {
103 guard precision <= 16 else { throw Unsupported("calc precision") }
104 guard case .float(let m, let e) = x, (-300...300).contains(e + digits(Int128(m)) - 1),
105 let d = Double("\(m)e\(e)") else { throw Unsupported("number size") }
106 let r = f(d)
107 guard r.isFinite else { throw Unsupported("infinite result") }
108 // `number-to-string`: the shortest text that reads back as the same double.
109 let pieces = r.description.split(separator: "e")
110 let text = String(pieces[0])
111 let point = text.firstIndex(of: ".").map { text.distance(from: $0, to: text.endIndex) - 1 } ?? 0
112 guard let mantissa = Int128(text.replacingOccurrences(of: ".", with: "")),
113 let exponent = Int(pieces.count > 1 ? String(pieces[1]) : "0") else { throw Unsupported("number") }
114 return try makeFloat(mantissa, exponent - point)
115 }
116
117 // Constants to 36 digits, rounded to the precision, as `math-defcache` gives them.
118 static func pi() throws -> Value { try makeFloat(314159265358979323846264338327950288, -35) }
119 static func piOver2() throws -> Value { try makeFloat(157079632679489661923132169163975144, -35) }
120 static func piOver4() throws -> Value { try makeFloat(785398163397448309615660845819875721, -36) }
121 static func twoPi() throws -> Value { try makeFloat(628318530717958647692528676655900577, -35) }
122 static func piOver180() throws -> Value { try makeFloat(174532925199432957692369076848861271, -37) }
123
124 /// `math-float`.
125 static func float(_ v: Value) throws -> Value {
126 switch v {
127 case .int(let i): return try makeFloat(Int128(i), 0)
128 case .frac(let n, let d): return try divide(try makeFloat(Int128(n), 0), .int(d))
129 case .float: return v
130 default: throw Unsupported("arguments")
131 }
132 }
133
134 static func isZero(_ v: Value) -> Bool { v == .int(0) || v == .float(0, 0) }
135
136 /// The sign of a real number.
137 static func sign(_ v: Value) throws -> Int {
138 switch v {
139 case .int(let i): return i.signum()
140 case .float(let m, _): return m.signum()
141 case .frac(let n, _): return n.signum()
142 default: throw Unsupported("arguments")
143 }
144 }
145
146 /// `math-trunc` of a real number, as an integer.
147 static func trunc(_ v: Value) throws -> Int {
148 switch v {
149 case .int(let i): return i
150 case .frac(let n, let d): return n / d
151 case .float(let m, let e):
152 let t = e >= 0 ? try scaleRounding(Int128(m), e) : -e > 37 ? 0 : Int128(m) / (try power10(-e))
153 guard let i = Int(exactly: t) else { throw Unsupported("integer size") }
154 return i
155 default: throw Unsupported("arguments")
156 }
157 }
158
159 /// `Math-num-integerp`: an integer, or a float with an integer value.
160 static func isWhole(_ v: Value) -> Bool {
161 switch v {
162 case .int: true
163 case .float(_, let e): e >= 0
164 default: false
165 }
166 }
167
168 /// `math-nearly-equal-float`: equal but for the last digit of precision.
169 static func nearlyEqual(_ a: Value, _ b: Value) -> Bool {
170 guard case .float(let ma, let ea) = a, case .float(let mb, let eb) = b else { return false }
171 let (x, y) = (Int128(ma), Int128(mb))
172 switch ea - eb {
173 case 0: return x == y || (abs(y - x) < 10 && digits(x) == precision)
174 case 1: return abs(x * 10 - y) < 10 && digits(y) == precision
175 case -1: return abs(y * 10 - x) < 10 && digits(x) == precision
176 default: return false
177 }
178 }
179
180 static func digits(_ x: Int128) -> Int {
181 var n = x.magnitude
182 var count = 1
183 while n >= 10 {
184 n /= 10
185 count += 1
186 }
187 return count
188 }
189
190 static func power10(_ n: Int) throws -> Int128 {
191 guard n >= 0, n <= 37 else { throw Unsupported("number size") }
192 var result: Int128 = 1
193 for _ in 0..<n { result *= 10 }
194 return result
195 }
196
197 /// `math-scale-rounding`: `x` times 10^n, rounding half away from zero when n < 0.
198 static func scaleRounding(_ x: Int128, _ n: Int) throws -> Int128 {
199 if n >= 0 {
200 let (result, overflow) = x.multipliedReportingOverflow(by: try power10(n))
201 if overflow { throw Unsupported("number size") }
202 return result
203 }
204 if x < 0 { return -(try scaleRounding(-x, n)) }
205 if -n > 38 { return 0 }
206 let truncated = -n - 1 > 37 ? 0 : x / (try power10(-n - 1))
207 return (truncated + 5) / 10
208 }
209
210 /// `math-make-float`.
211 static func makeFloat(_ mantissa: Int128, _ exponent: Int) throws -> Value {
212 var m = mantissa
213 var e = exponent
214 if m == 0 { return .float(0, 0) }
215 let excess = digits(m) - precision
216 if excess > 0 {
217 m = try scaleRounding(m, -excess)
218 e += excess
219 }
220 if m == 0 { return .float(0, 0) }
221 while m % 10 == 0 {
222 m /= 10
223 e += 1
224 }
225 // Calc signals `math-overflow` and `math-underflow` here and leaves the formula alone.
226 let magnitude = e + digits(m) - 1
227 if magnitude >= 4_000_000 || magnitude <= -4_000_000 { throw Unsupported("number size") }
228 guard let i = Int(exactly: m) else { throw Unsupported("calc precision") }
229 return .float(i, e)
230 }
231
232 static func parts(_ v: Value) throws -> (Int128, Int) {
233 switch v {
234 // `math-float`: normalized and rounded, as Calc converts an integer to combine it with a float.
235 case .int(let i): return try parts(try makeFloat(Int128(i), 0))
236 case .float(let m, let e): return (Int128(m), e)
237 case .frac(let n, let d): return try parts(try divide(.int(n), .int(d)))
238 case .vector: throw Unsupported("vector arithmetic")
239 case .date, .nan: throw Unsupported("date arithmetic")
240 case .symbolic: throw Unsupported("symbolic arithmetic")
241 }
242 }
243
244 /// An integer or a fraction as numerator and denominator.
245 static func rational(_ v: Value) -> (Int, Int)? {
246 switch v {
247 case .int(let i): (i, 1)
248 case .frac(let n, let d): (n, d)
249 default: nil
250 }
251 }
252
253 /// `math-make-frac`: reduced, as an integer when it is one.
254 static func fraction(_ n: Int, _ d: Int) throws -> Value {
255 guard d != 0 else { throw Unsupported("division by zero") }
256 guard n != .min, d != .min else { throw Unsupported("integer size") }
257 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
258 let g = gcd(n, d)
259 var (num, den) = (n / g, d / g)
260 if den < 0 { (num, den) = (-num, -den) }
261 return den == 1 ? .int(num) : .frac(num, den)
262 }
263
264 /// Two rationals, one of them a fraction, combined exactly; nil otherwise.
265 static func exact(_ a: Value, _ b: Value, _ op: (Int, Int, Int, Int) -> (Int, Int, Bool)) throws -> Value? {
266 var fraction = false
267 if case .frac = a { fraction = true }
268 if case .frac = b { fraction = true }
269 guard fraction, let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { return nil }
270 let (n, d, overflow) = op(n1, d1, n2, d2)
271 if overflow { throw Unsupported("integer size") }
272 return try self.fraction(n, d)
273 }
274
275 static func double(_ v: Value) throws -> Double {
276 switch v {
277 case .int(let i): return Double(i)
278 case .float(let m, let e): return Double(m) * pow(10, Double(e))
279 case .frac(let n, let d): return Double(n) / Double(d)
280 case .vector: throw Unsupported("vector arithmetic")
281 case .date, .nan: throw Unsupported("date arithmetic")
282 case .symbolic: throw Unsupported("symbolic arithmetic")
283 }
284 }
285
286 static func isSymbolic(_ vs: Value...) -> Bool {
287 vs.contains { if case .symbolic = $0 { true } else { false } }
288 }
289
290 static func add(_ a: Value, _ b: Value) throws -> Value {
291 if isSymbolic(a, b) { return value(try Symbolic.add(try term(a), try term(b))) }
292 switch (a, b) {
293 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
294 case (.nan, _), (_, .nan): return .nan
295 // Two dates add as their day numbers.
296 case (.date(let x), .date(let y)): return try add(x, y)
297 case (.date(let d), _): return .date(try add(d, b))
298 case (_, .date(let d)): return .date(try add(a, d))
299 default: break
300 }
301 if case .int(let x) = a, case .int(let y) = b {
302 let (sum, overflow) = x.addingReportingOverflow(y)
303 if overflow { throw Unsupported("integer size") }
304 return .int(sum)
305 }
306 if let sum = try exact(a, b, { n1, d1, n2, d2 in
307 let (p, o1) = n1.multipliedReportingOverflow(by: d2)
308 let (q, o2) = n2.multipliedReportingOverflow(by: d1)
309 let (n, o3) = p.addingReportingOverflow(q)
310 let (d, o4) = d1.multipliedReportingOverflow(by: d2)
311 return (n, d, o1 || o2 || o3 || o4)
312 }) { return sum }
313 let (m1, e1) = try parts(a)
314 let (m2, e2) = try parts(b)
315 if m1 == 0 { return try makeFloat(m2, e2) }
316 if m2 == 0 { return try makeFloat(m1, e1) }
317 let ediff = e1 - e2
318 if ediff >= 0 {
319 if ediff >= 2 * precision { return try makeFloat(m1, e1) }
320 let (m, shift) = try align(m1, ediff, m2)
321 return try makeFloat(m, e2 + shift)
322 }
323 if -ediff >= 2 * precision { return try makeFloat(m2, e2) }
324 let (m, shift) = try align(m2, -ediff, m1)
325 return try makeFloat(m, e1 + shift)
326 }
327
328 /// `big` times 10^ediff plus `small`, and the power of ten that scales it. Past 37 digits
329 /// the digits of `small` below the precision become one sticky digit, which rounds the same.
330 static func align(_ big: Int128, _ ediff: Int, _ small: Int128) throws -> (Int128, Int) {
331 if digits(big) + ediff <= 37 { return (try scaleRounding(big, ediff) + small, 0) }
332 let s = max(precision + 2 - digits(big), 0)
333 let k = ediff - s
334 let (q, r) = k > 37 ? (0, small) : small.quotientAndRemainder(dividingBy: try power10(k))
335 return (try scaleRounding(big, s + 1) + q * 10 + r.signum(), k - 1)
336 }
337
338 static func negate(_ a: Value) throws -> Value {
339 switch a {
340 case .symbolic(let t): return value(try Symbolic.neg(t))
341 case .int(let i):
342 guard i != .min else { throw Unsupported("integer size") }
343 return .int(-i)
344 case .float(let m, let e): return .float(-m, e)
345 case .frac(let n, let d): return .frac(-n, d)
346 case .vector: throw Unsupported("vector arithmetic")
347 case .date(let d): return .date(try negate(d))
348 case .nan: return .nan
349 }
350 }
351
352 /// `a - b`: a date less a date is the days between them.
353 static func subtract(_ a: Value, _ b: Value) throws -> Value {
354 try add(a, try negate(b))
355 }
356
357 static func isNaN(_ a: Value, _ b: Value) -> Bool {
358 if case .vector = a { return false }
359 if case .vector = b { return false }
360 return a == .nan || b == .nan
361 }
362
363 static func multiply(_ a: Value, _ b: Value) throws -> Value {
364 if isSymbolic(a, b) { return value(try Symbolic.mul(try term(a), try term(b))) }
365 if isNaN(a, b) { return .nan }
366 if case .int(let x) = a, case .int(let y) = b {
367 let (product, overflow) = x.multipliedReportingOverflow(by: y)
368 if overflow { throw Unsupported("integer size") }
369 return .int(product)
370 }
371 if let product = try exact(a, b, { n1, d1, n2, d2 in
372 let (n, o1) = n1.multipliedReportingOverflow(by: n2)
373 let (d, o2) = d1.multipliedReportingOverflow(by: d2)
374 return (n, d, o1 || o2)
375 }) { return product }
376 let (m1, e1) = try parts(a)
377 let (m2, e2) = try parts(b)
378 let (product, overflow) = m1.multipliedReportingOverflow(by: m2)
379 if overflow { throw Unsupported("number size") }
380 return try makeFloat(product, e1 + e2)
381 }
382
383 static func divide(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
384 // `math-div-by-zero` leaves the quotient alone.
385 if isSymbolic(a, b) || (isZero(b) && (try? sign(a)) != nil) {
386 return try $fractions.withValue(fractions) { value(try Symbolic.div(try term(a), try term(b))) }
387 }
388 if isNaN(a, b) { return .nan }
389 if fractions || { if case .frac = a { return true }; if case .frac = b { return true }; return false }(),
390 let (n1, d1) = rational(a), let (n2, d2) = rational(b) {
391 guard n2 != 0 else { throw Unsupported("division by zero") }
392 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
393 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
394 if o1 || o2 { throw Unsupported("integer size") }
395 return try fraction(n, d)
396 }
397 if case .int(let x) = a, case .int(let y) = b {
398 guard y != 0 else { throw Unsupported("division by zero") }
399 if x % y == 0 { return .int(x / y) }
400 }
401 let (m1, e1) = try parts(a)
402 let (m2, e2) = try parts(b)
403 guard m2 != 0 else { throw Unsupported("division by zero") }
404 // `math-div-float`: scale so the truncated quotient has one digit more than needed.
405 let ldiff = max(precision + 1 - (digits(m1) - digits(m2)), 0)
406 let quotient = (try scaleRounding(m1, ldiff)) / m2
407 return try makeFloat(quotient, e1 - ldiff - e2)
408 }
409
410 static func isInteger(_ v: Value) -> Bool {
411 if case .int = v { return true }
412 return false
413 }
414
415 /// `math-ipow`.
416 static func integerPower(_ a: Value, _ n: Int, fractions: Bool = false) throws -> Value {
417 if n < 0 { return try integerPower(try divide(.int(1), a, fractions: fractions), -n) }
418 if n == 0 { return .int(1) }
419 if n == 1 { return a }
420 let square = try multiply(a, a)
421 if n % 2 == 0 { return try integerPower(square, n / 2) }
422 return try multiply(a, try integerPower(square, n / 2))
423 }
424
425 /// `math-pow` of real numbers.
426 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
427 // In symbolic mode Calc keeps a power that isn't exact, which isn't reproduced.
428 if symbolicMode, !isInteger(b) { throw Unsupported("symbolic mode") }
429 if isSymbolic(a, b) { return try $fractions.withValue(fractions) { value(try Symbolic.pow(try term(a), try term(b))) } }
430 if isNaN(a, b) { return .nan }
431 _ = (try sign(a), try sign(b))
432 var floatB = false
433 if case .float = b { floatB = true }
434 if isZero(a) {
435 // `math-pow-of-zero`: an indeterminate form, or a division by zero, stays alone.
436 if b == .int(0) { return .int(1) }
437 guard try sign(b) > 0 else { throw Rejected() }
438 return floatB ? try float(a) : a
439 }
440 if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a }
441 if isZero(b) {
442 if case .float = a { return .float(1, 0) }
443 return floatB ? .float(1, 0) : .int(1)
444 }
445 if case .int(let n) = b {
446 if a == .float(1, 1) { return try makeFloat(1, n) }
447 return try extra(2) { try integerPower(a, n, fractions: fractions) }
448 }
449 // `math-pow-fancy`.
450 if let q = quarter(b), (1...3).contains(q) {
451 let root = try squareRoot(floatB ? try float(a) : a)
452 return try power(root, try multiply(.int(2), b), fractions: fractions)
453 }
454 if case .frac(let num, let den) = b, den <= 10, try sign(a) > 0 {
455 return try integerPower(try nthRoot(a, den), num, fractions: fractions)
456 }
457 if a == .int(10) || a == .float(1, 1), isWhole(b) { return try makeFloat(1, try trunc(b)) }
458 guard try sign(a) > 0 else { throw Unsupported("complex result") }
459 return try extra(2) { try expRaw(try float(try multiply(b, try lnRaw(try float(a))))) }
460 }
461
462 /// `math-quarter-integer`: 0 for an integer, 1 to 3 for a number of quarters, else nil.
463 static func quarter(_ x: Value) -> Int? {
464 switch x {
465 case .int: return 0
466 case .frac(let n, let d):
467 if n < 0 { return quarter(.frac(-n, d)).map { 4 - $0 } }
468 return d == 2 ? 2 : d == 4 ? n % 4 : nil
469 case .float(let m, let e):
470 if m < 0 { return quarter(.float(-m, e)).map { 4 - $0 } }
471 if e >= 0 { return 0 }
472 if e == -1 { return m % 10 == 5 ? 2 : nil }
473 if e == -2 { return m % 100 == 25 ? 1 : m % 100 == 75 ? 3 : nil }
474 return nil
475 default: return nil
476 }
477 }
478
479 static func compare(_ a: Value, _ b: Value) throws -> Int {
480 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) }
481 if a == .nan || b == .nan { throw Unsupported("comparison with nan") }
482 // `math-compare` clears a fraction's denominator, so 0.333333333333 is less than 1:3.
483 let real = { (v: Value) in switch v { case .int, .float, .frac: true; default: false } }
484 if real(a), real(b) {
485 if case .frac(let n, let d) = a {
486 if case .frac(let n2, let d2) = b { return try compare(try multiply(.int(n), .int(d2)), try multiply(.int(n2), .int(d))) }
487 return try compare(.int(n), try multiply(b, .int(d)))
488 }
489 if case .frac(let n, let d) = b { return try compare(try multiply(a, .int(d)), .int(n)) }
490 }
491 let difference = try add(a, try negate(b))
492 let (m, _) = try parts(difference)
493 return m == 0 ? 0 : (m < 0 ? -1 : 1)
494 }
495
496 static func absolute(_ v: Value) throws -> Value { try sign(v) < 0 ? try negate(v) : v }
497
498 /// `math-floor` of a real number, as an integer.
499 static func floorInt(_ v: Value) throws -> Int {
500 let t = try trunc(v)
501 return try sign(v) < 0 && compare(v, .int(t)) != 0 ? t - 1 : t
502 }
503
504 // MARK: - Roots, logarithms and rounding
505
506 /// `math-sqrt` of a real number.
507 static func squareRoot(_ a: Value) throws -> Value {
508 if isZero(a) { return a }
509 guard try sign(a) > 0 else { throw Unsupported("complex result") }
510 func exact(_ i: Int) -> Int? {
511 let guess = Int(Double(i).squareRoot())
512 return [guess - 1, guess, guess + 1].first { $0 >= 0 && $0.multipliedReportingOverflow(by: $0) == (i, false) }
513 }
514 if case .int(let i) = a, let root = exact(i) { return .int(root) }
515 if case .frac(let n, let d) = a, let rn = exact(n), let rd = exact(d) { return .frac(rn, rd) }
516 let x = try float(a)
517 return try extra(1) { try squareRootRaw(x) }
518 }
519
520 /// `math-sqrt-raw` of a float.
521 static func squareRootRaw(_ a: Value) throws -> Value {
522 if isZero(a) { return a }
523 guard try sign(a) > 0 else { throw Unsupported("complex result") }
524 if precision <= 16 { return try emacs({ $0.squareRoot() }, a) }
525 // Newton's method from the root of the first six or seven digits.
526 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
527 var ldiff = digits(Int128(m)) - 6
528 if (e + ldiff) % 2 != 0 { ldiff += 1 }
529 let head = ldiff >= 0 ? Int128(m) / (try power10(ldiff)) : Int128(m) * (try power10(-ldiff))
530 var root = Int128(Double(head).squareRoot())
531 while root * root > head { root -= 1 }
532 while (root + 1) * (root + 1) <= head { root += 1 }
533 var guess = try makeFloat(root, (e + ldiff) / 2)
534 for _ in 0..<1000 {
535 let next = try multiply(try add(guess, try divide(a, guess)), .float(5, -1))
536 if nearlyEqual(next, guess) { return next }
537 guess = next
538 }
539 throw Unsupported("number")
540 }
541
542 /// `math-exp-raw` of a float.
543 static func expRaw(_ x: Value) throws -> Value {
544 isZero(x) ? .float(1, 0) : try emacs({ Foundation.exp($0) }, x)
545 }
546
547 /// `math-ln-raw` of a float.
548 static func lnRaw(_ x: Value) throws -> Value {
549 if x == .float(1, 0) { return .float(0, 0) }
550 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
551 return try emacs({ Foundation.log($0) }, x)
552 }
553
554 /// `math-arctan-raw` of a float.
555 static func arctanRaw(_ x: Value) throws -> Value {
556 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) }
557 if isZero(x) { return x }
558 if precision <= 16 { return try emacs({ Foundation.atan($0) }, x) }
559 if symbolicMode { throw Unsupported("symbolic mode") }
560 if x == .float(1, 0) { return try piOver4() }
561 if try compare(.float(414214, -6), x) < 0 {
562 if try compare(.float(1, 0), x) < 0 {
563 return try subtract(try multiply(try pi(), .float(5, -1)), try arctanRaw(try divide(.float(1, 0), x)))
564 }
565 let reduced = try divide(try subtract(.float(1, 0), x), try add(.float(1, 0), x))
566 return try subtract(try multiply(try pi(), .float(25, -2)), try arctanRaw(reduced))
567 }
568 // `math-arctan-series`.
569 let xnegsqr = try negate(try multiply(x, x))
570 var (sum, power, n) = (x, x, 3)
571 for _ in 0..<10000 {
572 power = try multiply(power, xnegsqr)
573 let next = try add(sum, try divide(power, try float(.int(n))))
574 if nearlyEqual(sum, next) { return sum }
575 (sum, n) = (next, n + 2)
576 }
577 throw Unsupported("number")
578 }
579
580 /// `math-arctan2-raw` of floats.
581 static func arctan2Raw(_ y: Value, _ x: Value) throws -> Value {
582 if isZero(y) { return try sign(x) < 0 ? try pi() : .float(0, 0) }
583 if isZero(x) { return try sign(y) > 0 ? try piOver2() : try negate(try piOver2()) }
584 if try sign(x) > 0 { return try arctanRaw(try divide(y, x)) }
585 if try sign(y) > 0 { return try add(try arctanRaw(try divide(y, x)), try pi()) }
586 // `math-sub-float` gives pi itself, not its negative, when the angle is too small to count.
587 let angle = try arctanRaw(try divide(y, x))
588 if case .float(_, let e) = angle, case .float(_, let ep) = try pi(), ep - e >= 2 * precision { return try pi() }
589 return try subtract(angle, try pi())
590 }
591
592 /// `math-arcsin-raw` of a real float.
593 static func arcsinRaw(_ x: Value) throws -> Value {
594 try arctan2Raw(x, try squareRootRaw(try subtract(.float(1, 0), try multiply(x, x))))
595 }
596
597 /// `math-sin-raw` of a real float; `orgx` is the argument before reduction.
598 static func sinRaw(_ x: Value, _ orgx: Value? = nil) throws -> Value {
599 let orgx = orgx ?? x
600 if try sign(x) < 0 { return try negate(try sinRaw(try negate(x), orgx)) }
601 if try compare(.float(7, 0), x) < 0 {
602 // `math-mod` by 2 pi.
603 let turns = try floorInt(try divide(x, try twoPi()))
604 return try sinRaw(try subtract(x, try multiply(.int(turns), try twoPi())), orgx)
605 }
606 return try sinRaw2(x, orgx)
607 }
608
609 /// `math-cos-raw` of a real float.
610 static func cosRaw(_ x: Value) throws -> Value {
611 try sinRaw(try subtract(try piOver2(), x), x)
612 }
613
614 /// `math-nearly-zerop-float`: `a` is zero next to `b`, at one digit less.
615 static func nearlyZero(_ a: Value, _ b: Value) -> Bool {
616 guard case .float(let ma, let ea) = a, case .float(let mb, let eb) = b else { return false }
617 return ma == 0 || digits(Int128(ma)) + ea <= 1 + (mb == 0 ? 0 : digits(Int128(mb))) + eb - (precision - 1)
618 }
619
620 /// `math-sin-raw-2`.
621 static func sinRaw2(_ x: Value, _ orgx: Value) throws -> Value {
622 let xmpo2 = try subtract(try piOver2(), x)
623 if try sign(xmpo2) < 0 { return try negate(try sinRaw2(try subtract(x, try pi()), orgx)) }
624 if try compare(try piOver4(), x) < 0 { return try cosRaw2(xmpo2, orgx) }
625 if try compare(x, try negate(try piOver4())) < 0 { return try negate(try cosRaw2(try add(try piOver2(), x), orgx)) }
626 if nearlyZero(x, orgx) { return .float(0, 0) }
627 if precision <= 16 { return try emacs({ Foundation.sin($0) }, x) }
628 if symbolicMode { throw Unsupported("symbolic mode") }
629 return try sinSeries(x, 6, 4, x, try negate(try multiply(x, x)))
630 }
631
632 /// `math-cos-raw-2`.
633 static func cosRaw2(_ x: Value, _ orgx: Value) throws -> Value {
634 if nearlyZero(x, orgx) { return .float(1, 0) }
635 if precision <= 16 { return try emacs({ Foundation.cos($0) }, x) }
636 if symbolicMode { throw Unsupported("symbolic mode") }
637 let xnegsqr = try negate(try multiply(x, x))
638 return try sinSeries(try add(.float(1, 0), try multiply(xnegsqr, .float(5, -1))), 24, 5, xnegsqr, xnegsqr)
639 }
640
641 /// `math-sin-series`.
642 static func sinSeries(_ sum: Value, _ nfac: Int, _ n: Int, _ x: Value, _ xnegsqr: Value) throws -> Value {
643 var (sum, nfac, n, x) = (sum, Value.int(nfac), n, x)
644 for _ in 0..<10000 {
645 x = try multiply(x, xnegsqr)
646 let next = try add(sum, try divide(x, try float(nfac)))
647 if nearlyEqual(sum, next) { return sum }
648 (sum, nfac, n) = (next, try multiply(nfac, .int(n * (n + 1))), n + 2)
649 }
650 throw Unsupported("number")
651 }
652
653 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) }
654 static func ln10() throws -> Value { try makeFloat(230258509299404568401799145468436421, -35) }
655
656 /// `math-ln-raw-2`: the logarithm of a positive float by Calc's series.
657 static func lnRaw2(_ x: Value) throws -> Value {
658 if try compare(.float(14, -1), x) < 0 { return try add(try lnRaw2(try multiply(x, .float(5, -1))), try ln2()) }
659 let y = try divide(try subtract(x, .float(1, 0)), try add(x, .float(1, 0)))
660 let square = try multiply(y, y)
661 var (sum, power, n) = (y, y, 3)
662 for _ in 0..<10000 {
663 power = try multiply(power, square)
664 let next = try add(sum, try divide(power, try float(.int(n))))
665 if nearlyEqual(sum, next) { return try multiply(sum, .float(2, 0)) }
666 (sum, n) = (next, n + 2)
667 }
668 throw Unsupported("number")
669 }
670
671 /// `math-nth-root-integer`: the integer root rounded down, and whether it is exact.
672 static func integerRoot(_ a: Int, _ n: Int) throws -> (Bool, Int) {
673 let a = Int128(a)
674 var guess = try power10((digits(a) + n - 1) / n)
675 while true {
676 var p: Int128 = 1
677 for _ in 0..<(n - 1) {
678 let (r, overflow) = p.multipliedReportingOverflow(by: guess)
679 if overflow { throw Unsupported("integer size") }
680 p = r
681 }
682 let (q, r) = a.quotientAndRemainder(dividingBy: p)
683 let (g2, r2) = (q + Int128(n - 1) * guess).quotientAndRemainder(dividingBy: Int128(n))
684 if g2 < guess {
685 guess = g2
686 continue
687 }
688 return (g2 == guess && r == 0 && r2 == 0, Int(guess))
689 }
690 }
691
692 /// `math-nth-root-float`: Newton's method at one digit more.
693 static func floatRoot(_ a: Value, _ n: Int, guess: Value? = nil) throws -> Value {
694 try extra(1) {
695 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
696 let nf = try makeFloat(Int128(n), 0)
697 let nfm1 = try makeFloat(Int128(n - 1), 0)
698 var g = try guess ?? makeFloat(1, (digits(Int128(m)) + e + n / 2) / n)
699 for _ in 0..<1000 {
700 let g2 = try divide(try add(try multiply(nfm1, g), try divide(a, try integerPower(g, n - 1))), nf)
701 if nearlyEqual(g2, g) { return g2 }
702 g = g2
703 }
704 throw Unsupported("number")
705 }
706 }
707
708 /// `math-nth-root` of a positive real number.
709 static func nthRoot(_ a: Value, _ n: Int) throws -> Value {
710 switch a {
711 case .int(let i):
712 let (exact, root) = try integerRoot(i, n)
713 return exact ? .int(root) : try floatRoot(try float(a), n, guess: try float(.int(root)))
714 case .frac(let num, let den):
715 let (e1, r1) = try integerRoot(num, n)
716 let (e2, r2) = try integerRoot(den, n)
717 if e1 && e2 { return .frac(r1, r2) }
718 return try floatRoot(try float(a), n, guess: try divide(try float(.int(r1)), try float(.int(r2))))
719 default:
720 return try floatRoot(a, n)
721 }
722 }
723
724 /// `math-pow` of a real number to the power `1:n`.
725 static func rootPower(_ a: Value, _ n: Int) throws -> Value {
726 if isZero(a) || a == .int(1) || a == .float(1, 0) { return a }
727 guard try sign(a) > 0 else { throw Unsupported("complex result") }
728 switch n {
729 case 1: return a
730 case 2: return try squareRoot(a)
731 case 4: return try squareRoot(try squareRoot(a))
732 case 3...10: return try nthRoot(a, n)
733 default: return try extra(2) { try expRaw(try float(try multiply(.frac(1, n), try lnRaw(try float(a))))) }
734 }
735 }
736
737 /// `math-integer-log`: the largest n with b^n at most x, and whether b^n is x.
738 static func integerLog(_ x: Value, _ b: Value) throws -> (Bool, Int) {
739 var pows = [b]
740 var pow = try multiply(b, b)
741 while try compare(x, pow) >= 0 {
742 pows.insert(pow, at: 0)
743 pow = try multiply(pow, pow)
744 }
745 var n = 1 << (pows.count - 1)
746 var sum = n
747 pow = pows[0]
748 var rest = pows.dropFirst()
749 while let next = rest.first, try compare(pow, x) < 0 {
750 rest = rest.dropFirst()
751 n /= 2
752 let candidate = try multiply(pow, next)
753 if try compare(x, candidate) >= 0 {
754 pow = candidate
755 sum += n
756 }
757 }
758 return (pow == x, sum)
759 }
760
761 /// `math-round` in `math-rounding-mode` `even` or `up`, or with `away` the default mode,
762 /// which rounds halves away from zero.
763 static func round(_ a: Value, even: Bool, away: Bool = false) throws -> Value {
764 if isWhole(a) { return .int(try trunc(a)) }
765 if try sign(a) < 0, even || away { return try negate(try round(try negate(a), even: even)) }
766 let b = try add(a, rational(a) != nil ? .frac(1, 2) : .float(5, -1))
767 var f = try floorInt(b)
768 if even, isWhole(b), f % 2 != 0 { f -= 1 }
769 return .int(f)
770 }
771
772 /// `calcFunc-scf`: `x` times 10^n.
773 static func scale(_ x: Value, _ n: Int, fractions: Bool) throws -> Value {
774 if n == 0 { return x }
775 guard abs(n) <= 18 else { throw Unsupported("number size") }
776 let p = Int(try power10(abs(n)))
777 switch x {
778 case .int: return n > 0 ? try multiply(x, .int(p)) : try divide(x, .int(p), fractions: fractions)
779 case .frac(let a, let b):
780 let (num, o1) = a.multipliedReportingOverflow(by: n > 0 ? p : 1)
781 let (den, o2) = b.multipliedReportingOverflow(by: n > 0 ? 1 : p)
782 if o1 || o2 { throw Unsupported("integer size") }
783 return try fraction(num, den)
784 case .float(let m, let e): return try makeFloat(Int128(m), e + n)
785 default: throw Unsupported("arguments")
786 }
787 }
788
789 /// `calcFunc-frac`: the fraction closest to a float within its precision.
790 static func toFraction(_ a: Value) throws -> Value {
791 if rational(a) != nil { return a }
792 if isWhole(a) { return .int(try trunc(a)) }
793 if try sign(a) < 0 { return try negate(try toFraction(try negate(a))) }
794 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
795 let tolerance = Value.float(5, digits(Int128(m)) + e - (1 + precision))
796 /// `math-eval-continued-fraction`.
797 func evaluate(_ terms: [Int], fractions: Bool) throws -> Value {
798 var n = Value.int(terms.last!)
799 var d = Value.int(1)
800 for c in terms.reversed().dropFirst() { (n, d) = (try add(try multiply(.int(c), n), d), n) }
801 return try divide(n, d, fractions: fractions)
802 }
803 let terms = try $precision.withValue(precision + 2) {
804 var terms: [Int] = []
805 var aa = a
806 while try terms.isEmpty || (!isZero(aa) && compare(try absolute(try subtract(a, try evaluate(terms, fractions: false))), tolerance) >= 0) {
807 guard terms.count < 100 else { throw Unsupported("number") }
808 let whole = try trunc(aa)
809 aa = try subtract(aa, .int(whole))
810 terms.append(whole)
811 if !isZero(aa) { aa = try divide(.int(1), aa) }
812 }
813 return terms
814 }
815 return try evaluate(terms, fractions: true)
816 }
817
818 /// `calcFunc-gcd`.
819 static func gcd(_ a: Value, _ b: Value) throws -> Value {
820 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
821 let a = isWhole(a) ? .int(try trunc(a)) : a
822 let b = isWhole(b) ? .int(try trunc(b)) : b
823 if case .int(let x) = a, case .int(let y) = b {
824 guard x != .min, y != .min else { throw Unsupported("integer size") }
825 return .int(gcd(x, y))
826 }
827 if try sign(a) < 0 { return try Calc.gcd(try negate(a), b) }
828 if try sign(b) < 0 { return try Calc.gcd(a, try negate(b)) }
829 guard let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { throw Unsupported("arguments") }
830 guard case .int(let g) = try Calc.gcd(.int(d1), .int(d2)) else { throw Unsupported("arguments") }
831 let (product, overflow) = d1.multipliedReportingOverflow(by: d2 / g)
832 if overflow { throw Unsupported("integer size") }
833 return try fraction(gcd(n1, n2), product)
834 }
835
836 /// `calcFunc-choose` of integers.
837 static func choose(_ n: Int, _ m: Int) throws -> Int {
838 if m >= 0, m <= n {
839 var c = 1
840 var top = n
841 for i in stride(from: 1, through: m > n / 2 ? n - m : m, by: 1) {
842 let (product, overflow) = c.multipliedReportingOverflow(by: top)
843 if overflow { throw Unsupported("integer size") }
844 c = product / i
845 top -= 1
846 }
847 return c
848 }
849 if n < 0, m >= 0 {
850 let v = try choose(m - n - 1, m)
851 return m % 2 == 0 ? v : -v
852 }
853 if n < 0 {
854 if n < m { return 0 }
855 let v = try choose(-m - 1, n - m)
856 return (n - m) % 2 == 0 ? v : -v
857 }
858 return 0
859 }
860
861 // MARK: - Display
862
863 /// `math-constp` of the values here: a real number, or a vector of them.
864 static func isConstant(_ v: Value) -> Bool {
865 switch v {
866 case .int, .float, .frac: true
867 case .vector(let items): items.allSatisfy(isConstant)
868 default: false
869 }
870 }
871
872 /// `math-format-number`.
873 static func format(_ value: Value, _ floatFormat: FloatFormat) throws -> String {
874 switch value {
875 case .int(let i): return String(i)
876 case .frac(let n, let d): return "\(n):\(d)"
877 case .vector(let items):
878 guard isConstant(value) else { throw Unsupported("vector result") }
879 return "[" + (try items.map { try format($0, floatFormat) }).joined(separator: ", ") + "]"
880 case .symbolic(let t): return try Symbolic.format(t, floatFormat)
881 case .nan: return "nan"
882 case .date(let d): return "<" + (try formatDate(d)) + ">"
883 case .float(let m, _) where m < 0:
884 guard case .float(let m, let e) = value else { fatalError() }
885 return "-" + (try format(.float(-m, e), floatFormat))
886 case .float(let m, var exp):
887 var mant = Int128(m)
888 var figs: Int
889 let kind: String
890 switch floatFormat {
891 case .float(let n): (figs, kind) = (n, "float")
892 case .fix(let n): (figs, kind) = (n, "fix")
893 case .sci(let n): (figs, kind) = (n, "sci")
894 case .eng(let n): (figs, kind) = (n, "eng")
895 }
896 // `math-numdigs` of zero is 0, so zero with no decimal places goes to scientific.
897 if kind == "fix", figs < 0 || exp + (mant == 0 ? 0 : digits(mant)) > -figs {
898 if figs < 0 { figs = -figs }
899 mant = try scaleRounding(mant, exp + figs)
900 var str = String(mant)
901 if str.count <= figs { str = String(repeating: "0", count: figs + 1 - str.count) + str }
902 if figs > 0 {
903 return String(str.dropLast(figs)) + "." + String(str.suffix(figs))
904 }
905 return str + "."
906 }
907 if figs < 0 { figs += precision }
908 if figs > 0 {
909 let adj = figs - digits(mant)
910 if adj < 0 {
911 mant = try scaleRounding(mant, adj)
912 exp -= adj
913 }
914 }
915 var str = String(mant)
916 let len = str.count
917 let dpos = exp + len
918 // `calc-display-sci-high` 0, `calc-display-sci-low` -3.
919 if kind == "float", dpos <= precision, dpos >= -1 {
920 if dpos == 0 {
921 str = "0." + str
922 } else if exp <= 0, dpos > 0 {
923 str = String(str.prefix(dpos)) + "." + String(str.dropFirst(dpos))
924 } else if exp > 0 {
925 str += String(repeating: "0", count: exp) + "."
926 } else {
927 str = "0." + String(repeating: "0", count: -dpos) + str
928 }
929 return str
930 }
931 let eadj = exp + len
932 let scale = kind == "eng" ? 1 + ((eadj + 300002) % 3) : 1
933 if scale > str.count { str += String(repeating: "0", count: scale - str.count) }
934 if scale < str.count { str = String(str.prefix(scale)) + "." + String(str.dropFirst(scale)) }
935 return str + "e" + String(eadj - scale)
936 }
937 }
938
939 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
940
941 /// `calc-date-format` as Org sets it: `YYYY-MM-DD Www`, then ` hh:mm` for a day number
942 /// that isn't an integer.
943 static func formatDate(_ value: Value) throws -> String {
944 let dt = try dateParts(value)
945 let year = dt.year > 0 && dt.year < 100 ? "+\(dt.year)" : String(dt.year)
946 var text = year + String(format: "-%02d-%02d ", dt.month, dt.day) + weekdays[Days.weekday(try floorInt(value))]
947 if let time = dt.time { text += String(format: " %02d:%02d", time.hour, time.minute) }
948 return text
949 }
950
951 /// A date form `<YYYY-MM-DD Www>` or `<YYYY-MM-DD Www hh:mm>`, from the text between
952 /// the brackets.
953 static func parseDate(_ text: String) throws -> Value {
954 guard let m = text.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?: +[A-Za-z]+)?(?: +([0-9]{1,2}):([0-9]{2})(?::([0-9]{2}))?)?$/) else {
955 throw Unsupported("date syntax")
956 }
957 // `math-parse-date-validate`: a year under 100 is 19xx or 20xx.
958 var year = Int(m.1)!
959 if year < 100 { year += year < 40 ? 2000 : 1900 }
960 let day = Days.absolute(year: year, month: Int(m.2)!, day: Int(m.3)!)
961 guard let hour = m.4.flatMap({ Int($0) }), let minute = m.5.flatMap({ Int($0) }) else { return .date(.int(day)) }
962 return try dateTime(day, hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0))
963 }
964
965 // MARK: - Dates
966
967 /// Calc numbers years without a year 0: -1 comes before 1.
968 static func astronomical(_ year: Int) -> Int { year > 0 ? year : year == 0 ? 0 : year + 1 }
969
970 /// `math-absolute-from-gregorian-dt`.
971 static func absolute(_ year: Int, _ month: Int, _ day: Int) throws -> Int {
972 guard abs(year) < 1_000_000_000 else { throw Unsupported("number size") }
973 return Days.absolute(year: astronomical(year), month: month, day: day)
974 }
975
976 /// `math-days-in-month`.
977 static func daysInMonth(_ year: Int, _ month: Int) throws -> Int {
978 try absolute(year, month + 1, 1) - absolute(year, month, 1)
979 }
980
981 /// `math-dt-to-date` with a time of day: a float day number.
982 static func dateTime(_ day: Int, _ seconds: Int) throws -> Value {
983 .date(try add(try float(.int(day)), try divide(.int(seconds), .float(864, 2))))
984 }
985
986 /// `math-dt-to-date`.
987 static func dateValue(_ year: Int, _ month: Int, _ day: Int, _ time: (hour: Int, minute: Int, second: Int)? = nil) throws -> Value {
988 guard (1...12).contains(month), (1...31).contains(day) else { throw Unsupported("arguments") }
989 let n = try absolute(year, month, day)
990 guard let time else { return .date(.int(n)) }
991 guard [time.hour, time.minute, time.second].allSatisfy({ abs($0) < 1_000_000 }) else { throw Unsupported("arguments") }
992 return try dateTime(n, time.hour * 3600 + time.minute * 60 + time.second)
993 }
994
995 /// The day number of a date form, or a real number, which Calc's date functions also take.
996 static func dayNumber(_ v: Value) throws -> Value {
997 let x: Value = if case .date(let d) = v { d } else { v }
998 _ = try sign(x)
999 return x
1000 }
1001
1002 /// `math-date-to-dt`: the day, with the time of day when the day number isn't an integer.
1003 static func dateParts(_ v: Value) throws -> (year: Int, month: Int, day: Int, time: (hour: Int, minute: Int, second: Int)?) {
1004 let x = try dayNumber(v)
1005 let day = try floorInt(x)
1006 guard abs(day) < 100_000_000_000 else { throw Unsupported("number size") }
1007 let date = Days.date(day)
1008 let year = date.year > 0 ? date.year : date.year - 1
1009 if case .int = x { return (year, date.month, date.day, nil) }
1010 // Above 12 digits Calc keeps fractions of a second.
1011 guard precision <= 12 else { throw Unsupported("calc precision") }
1012 let seconds = try trunc(try round(try multiply(try subtract(x, .int(day)), .int(86400)), even: false))
1013 return (year, date.month, date.day, (seconds / 3600, seconds / 60 % 60, seconds % 60))
1014 }
1015
1016 /// `math-to-business-day`, with Calc's default holidays: Saturdays and Sundays.
1017 static func toBusinessDay(_ v: Value) throws -> (Value, holiday: Bool) {
1018 let x = try dayNumber(v)
1019 let day = try floorInt(x)
1020 try checkHolidayRange(day)
1021 let weekday = Days.weekday(day)
1022 let delta = day / 7 * 2 + (weekday > 0 ? 1 : 0)
1023 return (try add(.int(day - delta), try subtract(x, .int(day))), weekday == 0 || weekday == 6)
1024 }
1025
1026 /// `math-setup-holidays` with a date: Calc's holidays cover the years 1 to 2737.
1027 static func checkHolidayRange(_ day: Int) throws {
1028 guard (try absolute(1, 1, 1)...absolute(2737, 12, 31)).contains(day) else { throw Unsupported("arguments") }
1029 }
1030
1031 /// `math-from-business-day`.
1032 static func fromBusinessDay(_ n: Value) throws -> Value {
1033 var day = try floorInt(n)
1034 let time = try subtract(n, .int(day))
1035 var left = ((day % 5) + 5) % 5
1036 day += day / 5 * 2
1037 var weekday = 0
1038 while true {
1039 if weekday == 0 || weekday == 6 {
1040 day += 1
1041 } else {
1042 left -= 1
1043 if left < 0 { break }
1044 }
1045 weekday += 1
1046 }
1047 try checkHolidayRange(day)
1048 return .date(try add(.int(day), time))
1049 }
1050
1051 /// `calcFunc-tzone` for the local zone, in seconds. Calc applies the current year's
1052 /// daylight saving rules to every date, which isn't reproduced, so only zones without
1053 /// daylight saving time are supported.
1054 static func zoneOffset(_ zone: TimeZone) throws -> Int {
1055 guard !zone.isDaylightSavingTime(), zone.nextDaylightSavingTimeTransition == nil else {
1056 throw Unsupported("daylight saving time")
1057 }
1058 return -zone.secondsFromGMT()
1059 }
1060
1061 // MARK: - Parsing
1062
1063 indirect enum Node {
1064 case number(Value)
1065 case vector([Node])
1066 case unary(Character, Node)
1067 case binary(Character, Node, Node)
1068 case call(String, [Node])
1069 case variable(String)
1070
1071 /// Whether the formula has a quotient, a power, a function call, or a product
1072 /// whose factors share a variable, which Calc simplifies to a power.
1073 var mayExplain: Bool {
1074 switch self {
1075 case .number, .variable: false
1076 case .call: true
1077 case .vector(let items): items.contains { $0.mayExplain }
1078 case .unary(_, let a): a.mayExplain
1079 case .binary("*", let a, let b) where !a.variables.isDisjoint(with: b.variables): true
1080 case .binary(let op, let a, let b): "/%\\^".contains(op) || a.mayExplain || b.mayExplain
1081 }
1082 }
1083
1084 var variables: Set<String> {
1085 switch self {
1086 case .number: []
1087 case .variable(let name): [name]
1088 case .call(_, let items), .vector(let items): items.reduce(into: []) { $0.formUnion($1.variables) }
1089 case .unary(_, let a): a.variables
1090 case .binary(_, let a, let b): a.variables.union(b.variables)
1091 }
1092 }
1093 }
1094
1095 struct Parser {
1096 let chars: [Character]
1097 var i = 0
1098 /// Inside `[...]`, where Calc reads `x -1` as two elements.
1099 var inVector = false
1100 /// Inside `[...]` with no comma, where Calc reads `1 2` as two elements.
1101 var spaceSeparated = false
1102
1103 init(_ s: String) { chars = Array(s) }
1104
1105 mutating func skip() {
1106 while i < chars.count, chars[i] == " " || chars[i] == "\t" { i += 1 }
1107 }
1108
1109 mutating func peek() -> Character? {
1110 skip()
1111 return i < chars.count ? chars[i] : nil
1112 }
1113
1114 mutating func parse() throws -> Node {
1115 let node = try or()
1116 guard peek() == nil else { throw Unsupported("formula syntax") }
1117 return node
1118 }
1119
1120 mutating func take(_ token: String) -> Bool {
1121 guard peek() != nil else { return false }
1122 let t = Array(token)
1123 guard i + t.count <= chars.count, Array(chars[i..<(i + t.count)]) == t else { return false }
1124 i += t.count
1125 return true
1126 }
1127
1128 // `||` < `&&` < comparisons < sums.
1129 mutating func or() throws -> Node {
1130 var left = try and()
1131 while take("||") { left = .binary("|", left, try and()) }
1132 return left
1133 }
1134
1135 mutating func and() throws -> Node {
1136 var left = try comparison()
1137 while take("&&") { left = .binary("&", left, try comparison()) }
1138 return left
1139 }
1140
1141 mutating func comparison() throws -> Node {
1142 let left = try sum()
1143 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
1144 if take("<<") || take(">>") { throw Unsupported("formula syntax") }
1145 // In a vector without commas Calc reads `<` after a space as the start of a date:
1146 // `[0 < (1 > 2)]` is `[0, <2026-01-02 Fri>]`.
1147 if spaceSeparated, peek() == "<", chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, !"=<>".contains(chars[i + 1]) {
1148 throw Unsupported("formula syntax")
1149 }
1150 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
1151 let right = try sum()
1152 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
1153 return .binary(Character(op), left, right)
1154 }
1155 return left
1156 }
1157
1158 // `+ -` < `/` < `*` < unary minus < `^`, as Calc's operator table orders them.
1159 mutating func sum() throws -> Node {
1160 var left = try quotient()
1161 while let c = peek(), c == "+" || c == "-" {
1162 if inVector, i > 0, chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, chars[i + 1] != " ", chars[i + 1] != "\t" {
1163 throw Unsupported("formula syntax")
1164 }
1165 i += 1
1166 left = .binary(c, left, try quotient())
1167 }
1168 return left
1169 }
1170
1171 mutating func quotient() throws -> Node {
1172 var left = try product()
1173 while let c = peek(), c == "/" || c == "%" || c == "\\" {
1174 i += 1
1175 left = .binary(c, left, try product())
1176 }
1177 return left
1178 }
1179
1180 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`. With
1181 /// `calc-multiplication-has-precedence` both are right-associative: `a * b c` and
1182 /// `a * b * c` are `a * (b * c)`.
1183 mutating func product() throws -> Node {
1184 let left = try unary()
1185 guard let c = peek() else { return left }
1186 if c == "*" {
1187 i += 1
1188 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
1189 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
1190 return left
1191 } else if spaceSeparated, chars[i - 1] == " " || chars[i - 1] == "\t" {
1192 // Calc reads `[1 2]` as two elements and `[1 2 * 3]` as one; not reproduced.
1193 throw Unsupported("formula syntax")
1194 }
1195 return .binary("*", left, try product())
1196 }
1197
1198 /// `math-factor-after`: whether what follows can start an operand, which makes `%`
1199 /// the modulo operator rather than percent.
1200 func factorAfter(_ j: Int) -> Bool {
1201 var j = j
1202 while j < chars.count, chars[j] == " " || chars[j] == "\t" { j += 1 }
1203 guard j < chars.count else { return false }
1204 let c = chars[j]
1205 if c == ".", j + 1 < chars.count { return chars[j + 1].isASCII && chars[j + 1].isNumber }
1206 return (c.isASCII && c.isNumber) || c.isLetter || "$#\"-+!([{".contains(c)
1207 }
1208
1209 mutating func unary() throws -> Node {
1210 if let c = peek(), c == "-" || c == "+" {
1211 i += 1
1212 let operand = try unary()
1213 return c == "-" ? .unary("-", operand) : operand
1214 }
1215 return try powerNode()
1216 }
1217
1218 /// Prefix `!`, whose operand Calc reads at precedence 1000: `!x^2` is `(!x)^2`, and
1219 /// only a postfix `%` joins the operand. After `-` the operand is read as `-`'s.
1220 mutating func not() throws -> Node? {
1221 guard peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" else { return nil }
1222 // Calc reads `!!` as one token.
1223 if i + 1 < chars.count, chars[i + 1] == "!" { throw Unsupported("formula syntax") }
1224 i += 1
1225 if peek() == "-" { return .unary("!", try unary()) }
1226 var operand = try not() ?? primary()
1227 while peek() == "%", !factorAfter(i + 1) {
1228 if i + 1 < chars.count, chars[i + 1] == "%" { throw Unsupported("formula syntax") }
1229 i += 1
1230 operand = .call("percent", [operand])
1231 }
1232 return .unary("!", operand)
1233 }
1234
1235 mutating func powerNode() throws -> Node {
1236 var base = try not() ?? primary()
1237 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
1238 while let c = peek() {
1239 let next = i + 1 < chars.count ? chars[i + 1] : nil
1240 if c == "%", !factorAfter(i + 1) {
1241 // `%%` starts a comment.
1242 if next == "%" { throw Unsupported("formula syntax") }
1243 i += 1
1244 base = .call("percent", [base])
1245 } else if c == "!", next != "=" {
1246 if next == "!" {
1247 if i + 2 < chars.count, chars[i + 2] == "!" { throw Unsupported("formula syntax") }
1248 i += 2
1249 base = .call("dfact", [base])
1250 } else {
1251 i += 1
1252 base = .call("fact", [base])
1253 }
1254 } else {
1255 break
1256 }
1257 }
1258 if peek() == "^" {
1259 i += 1
1260 return .binary("^", base, try unary())
1261 }
1262 return base
1263 }
1264
1265 mutating func primary() throws -> Node {
1266 guard let c = peek() else { throw Unsupported("formula syntax") }
1267 if c == "(" {
1268 i += 1
1269 let outer = (inVector, spaceSeparated)
1270 (inVector, spaceSeparated) = (false, false)
1271 let inner = try or()
1272 (inVector, spaceSeparated) = outer
1273 guard peek() == ")" else { throw Unsupported("formula syntax") }
1274 i += 1
1275 return inner
1276 }
1277 if c == "[" {
1278 i += 1
1279 let outer = (inVector, spaceSeparated)
1280 (inVector, spaceSeparated) = (true, !hasComma())
1281 defer { (inVector, spaceSeparated) = outer }
1282 var items: [Node] = []
1283 if peek() != "]" {
1284 items.append(try or())
1285 while peek() == "," {
1286 i += 1
1287 items.append(try or())
1288 }
1289 }
1290 guard peek() == "]" else { throw Unsupported("formula syntax") }
1291 i += 1
1292 return .vector(items)
1293 }
1294 if c.isASCII, c.isNumber || c == "." { return .number(try number()) }
1295 if c == "<" {
1296 guard let close = chars[i...].firstIndex(of: ">") else { throw Unsupported("formula syntax") }
1297 let text = String(chars[(i + 1)..<close])
1298 i = close + 1
1299 return .number(try parseDate(text))
1300 }
1301 if c.isLetter {
1302 var name = ""
1303 while i < chars.count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
1304 name.append(chars[i])
1305 i += 1
1306 }
1307 // `[f (x)]` is two elements.
1308 if spaceSeparated, i < chars.count, chars[i] != "(", peek() == "(" { throw Unsupported("formula syntax") }
1309 guard peek() == "(" else {
1310 if name == "nan" { return .number(.nan) }
1311 // Calc's names are letters and digits; `_` is a subscript, and `'` and `#`
1312 // belong to the name.
1313 guard name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }), !reserved.contains(name),
1314 i >= chars.count || !"'#".contains(chars[i]) else { throw Unsupported("variable \(name)") }
1315 return .variable(name)
1316 }
1317 i += 1
1318 let outer = (inVector, spaceSeparated)
1319 (inVector, spaceSeparated) = (false, false)
1320 defer { (inVector, spaceSeparated) = outer }
1321 var args: [Node] = []
1322 if peek() != ")" {
1323 args.append(try or())
1324 while peek() == "," {
1325 i += 1
1326 args.append(try or())
1327 }
1328 }
1329 guard peek() == ")" else { throw Unsupported("formula syntax") }
1330 i += 1
1331 return .call(name, args)
1332 }
1333 throw Unsupported("formula syntax")
1334 }
1335
1336 /// `math-check-for-commas`: whether a comma follows before the bracket that closes.
1337 func hasComma() -> Bool {
1338 var depth = 0
1339 for c in chars[i...] {
1340 if "[{(".contains(c) { depth += 1 }
1341 if "]})".contains(c) { depth -= 1 }
1342 if depth < 0 { return false }
1343 if c == ",", depth == 0 { return true }
1344 }
1345 return false
1346 }
1347
1348 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
1349 /// and `1:2:3`, and integers in a radix, `16#FF`.
1350 mutating func number() throws -> Value {
1351 var whole = ""
1352 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
1353 whole.append(chars[i])
1354 i += 1
1355 }
1356 if !whole.isEmpty, i + 1 < chars.count, chars[i] == ":", chars[i + 1].isASCII, chars[i + 1].isNumber {
1357 var text = whole
1358 while i < chars.count, chars[i] == ":" || (chars[i].isASCII && chars[i].isNumber) {
1359 text.append(chars[i])
1360 i += 1
1361 }
1362 let parts = text.split(separator: ":", omittingEmptySubsequences: false).map { Int($0) }
1363 guard parts.count <= 3, !parts.contains(nil) else { throw Unsupported("formula syntax") }
1364 let n = parts.map { $0! }
1365 guard n.last != 0 else { throw Unsupported("formula syntax") }
1366 if n.count == 2 { return try fraction(n[0], n[1]) }
1367 let (product, o1) = n[0].multipliedReportingOverflow(by: n[2])
1368 let (sum, o2) = product.addingReportingOverflow(n[1])
1369 if o1 || o2 { throw Unsupported("integer size") }
1370 return try fraction(sum, n[2])
1371 }
1372 if !whole.isEmpty, i < chars.count, chars[i] == "#" {
1373 i += 1
1374 var text = ""
1375 while i < chars.count, chars[i].isASCII, chars[i].isLetter || chars[i].isNumber || chars[i] == "." || chars[i] == ":" || chars[i] == "#" {
1376 text.append(chars[i])
1377 i += 1
1378 }
1379 guard let radix = Int(whole), (2...36).contains(radix), !text.isEmpty,
1380 let value = Int(text, radix: radix) else { throw Unsupported("formula syntax") }
1381 return .int(value)
1382 }
1383 var fraction: String?
1384 // `2..5` is an interval, not `2.` then `.5`.
1385 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1386 i += 1
1387 var f = ""
1388 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
1389 f.append(chars[i])
1390 i += 1
1391 }
1392 fraction = f
1393 // Calc reads digits and points as one number: `21.11.2026` is a bad format.
1394 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1395 while i < chars.count, (chars[i].isASCII && chars[i].isNumber)
1396 || (chars[i] == "." && (i + 1 >= chars.count || chars[i + 1] != ".")) { i += 1 }
1397 // The position is in the string Calc reads, after it rewrites `..` and
1398 // characters such as `²`; an exponent belongs to the number.
1399 let before = String(chars[..<i])
1400 guard before.allSatisfy(\.isASCII), !before.contains(".."),
1401 i >= chars.count || !"eE".contains(chars[i]) else { throw Unsupported("formula syntax") }
1402 throw Failure("Bad format", position: i)
1403 }
1404 }
1405 var exponent: Int?
1406 if i < chars.count, chars[i] == "e" || chars[i] == "E" {
1407 var j = i + 1
1408 var e = ""
1409 if j < chars.count, chars[j] == "-" || chars[j] == "+" {
1410 e.append(chars[j])
1411 j += 1
1412 }
1413 var digitsSeen = false
1414 while j < chars.count, chars[j].isASCII, chars[j].isNumber {
1415 e.append(chars[j])
1416 j += 1
1417 digitsSeen = true
1418 }
1419 if digitsSeen {
1420 exponent = Int(e)
1421 i = j
1422 }
1423 }
1424 guard !whole.isEmpty || !(fraction ?? "").isEmpty else { throw Unsupported("formula syntax") }
1425 if fraction == nil, exponent == nil {
1426 guard let value = Int(whole) else { throw Unsupported("integer size") }
1427 return .int(value)
1428 }
1429 let digitsText = whole + (fraction ?? "")
1430 guard let mantissa = Int128(digitsText.isEmpty ? "0" : digitsText) else { throw Unsupported("number size") }
1431 return try makeFloat(mantissa, (exponent ?? 0) - (fraction?.count ?? 0))
1432 }
1433 }
1434
1435 // MARK: - Evaluation
1436
1437 struct Evaluator {
1438 let modes: Modes
1439
1440 func eval(_ node: Node) throws -> Value {
1441 switch node {
1442 case .number(let v): return v
1443 case .vector(let items): return .vector(try items.map(eval))
1444 case .unary("!", let operand):
1445 let a = try eval(operand)
1446 if isSymbolic(a) || a == .nan { return value(try Symbolic.function("lnot", [try term(a)])) }
1447 return .int(try truth(a) ? 0 : 1)
1448 case .unary(_, let operand):
1449 let a = try eval(operand)
1450 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) }
1451 case .binary(let op, let l, let r):
1452 let (a, b) = (try eval(l), try eval(r))
1453 if isSymbolic(a, b) || a == .nan || b == .nan, let name = Self.symbolicOperators[op] {
1454 return value(try Symbolic.function(name, [try term(a), try term(b)]))
1455 }
1456 do {
1457 return try binary(op, a, b)
1458 } catch is Rejected {
1459 // `math-normalize` keeps the operation, its arguments evaluated.
1460 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^", "%": "%"][op] else { throw Unsupported("division by zero") }
1461 return .symbolic(.op(name, [try term(a), try term(b)]))
1462 }
1463 case .call("if", let args) where args.count == 3:
1464 let c = try eval(args[0])
1465 // Calc keeps the branches of a formula's condition as written, and evaluates
1466 // only the branch a number's condition picks.
1467 if isSymbolic(c) || c == .nan { return .symbolic(.op("if", [try term(c), try literal(args[1]), try literal(args[2])])) }
1468 return try eval(try truth(c) ? args[1] : args[2])
1469 case .call(let name, let args):
1470 let values = try args.map(eval)
1471 // In symbolic mode Calc keeps these unevaluated when the result isn't exact,
1472 // which isn't reproduced.
1473 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) {
1474 throw Unsupported("function \(name) in symbolic mode")
1475 }
1476 // `nan` is a formula to these functions.
1477 if values.contains(where: Self.hasSymbol)
1478 || ((Symbolic.functions.contains(name) || name == "vmax" || name == "vmin") && values.contains(where: Self.hasNaN)) {
1479 // Calc leaves most functions of a formula alone, and simplifies some.
1480 let isVector = { (v: Value) in if case .vector = v { true } else { false } }
1481 if Symbolic.functions.contains(name), !values.contains(where: isVector) {
1482 return value(try Symbolic.function(name, try values.map(term)))
1483 }
1484 // `math-reduce-many-vecs`: `max` of the elements in turn, starting from
1485 // -inf (`inf` for `min`) when the first vector is empty.
1486 if name == "vmax" || name == "vmin", values.allSatisfy(isVector) {
1487 var items = try elements(values).map(term)
1488 if try elements([values[0]]).isEmpty {
1489 items.insert(name == "vmax" ? .op("neg", [Symbolic.inf]) : Symbolic.inf, at: 0)
1490 }
1491 return try extra(2) {
1492 value(try items.dropFirst().reduce(items[0]) { try Symbolic.function(name == "vmax" ? "max" : "min", [$0, $1]) })
1493 }
1494 }
1495 guard ["vsum", "vprod", "vmean", "vcount"].contains(name),
1496 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else {
1497 throw Unsupported("function \(name) of a formula")
1498 }
1499 }
1500 do {
1501 return try call(name, values)
1502 } catch is Rejected {
1503 throw Unsupported("division by zero")
1504 }
1505 case .variable(let name):
1506 return .symbolic(.variable(name))
1507 }
1508 }
1509
1510 static let symbolicOperators: [Character: String] = ["=": "eq", "≠": "neq", "<": "lt", ">": "gt", "≤": "leq", "≥": "geq",
1511 "&": "land", "|": "lor", "%": "%"]
1512
1513 /// A branch of `if` as Calc reads it, unevaluated.
1514 func literal(_ node: Node) throws -> Term {
1515 switch node {
1516 case .number, .variable: return try term(try eval(node))
1517 case .unary("-", let a):
1518 // The reader negates a number: `--3` is 3 and `-0.` is `0.`.
1519 let t = try literal(a)
1520 if case .number(let v) = t { return try term(try negate(v)) }
1521 return .op("neg", [t])
1522 case .binary(let op, let a, let b) where "+-*/^".contains(op): return .op(String(op), [try literal(a), try literal(b)])
1523 default: throw Unsupported("condition")
1524 }
1525 }
1526
1527 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr",
1528 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh",
1529 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"]
1530
1531 static func hasNaN(_ v: Value) -> Bool {
1532 switch v {
1533 case .nan: true
1534 case .vector(let items): items.contains(where: hasNaN)
1535 default: false
1536 }
1537 }
1538
1539 static func hasSymbol(_ v: Value) -> Bool {
1540 switch v {
1541 case .symbolic: true
1542 case .vector(let items): items.contains(where: hasSymbol)
1543 default: false
1544 }
1545 }
1546
1547 func binary(_ op: Character, _ a: Value, _ b: Value) throws -> Value {
1548 switch op {
1549 case "+": return try add(a, b)
1550 case "-": return try subtract(a, b)
1551 case "*": return try multiply(a, b)
1552 case "/": return try divide(a, b, fractions: modes.preferFractions)
1553 case "%": return try mod(a, b)
1554 case "\\": return try idiv(a, b)
1555 case "^": return try power(a, b, fractions: modes.preferFractions)
1556 // `calcFunc-lor` and `calcFunc-land` give one of their arguments.
1557 case "|": return try truth(a) ? a : b
1558 case "&": return try truth(a) ? b : a
1559 default:
1560 let order = try compare(a, b)
1561 let holds = switch op {
1562 case "=": order == 0
1563 case "≠": order != 0
1564 case "<": order < 0
1565 case ">": order > 0
1566 case "≤": order <= 0
1567 default: order >= 0
1568 }
1569 return .int(holds ? 1 : 0)
1570 }
1571 }
1572
1573 /// A condition's value: a number, nonzero for true.
1574 func truth(_ v: Value) throws -> Bool {
1575 switch v {
1576 case .int(let i): return i != 0
1577 case .float(let m, _): return m != 0
1578 case .frac: return true
1579 default: throw Unsupported("condition")
1580 }
1581 }
1582
1583 /// `math-mod`: the remainder with the divisor's sign.
1584 func mod(_ a: Value, _ b: Value) throws -> Value {
1585 if isZero(a), (try? sign(b)) != nil { return a }
1586 if isZero(b), (try? sign(a)) != nil { throw Rejected() }
1587 // `math-imod` only for natural numbers; otherwise the quotient is a float without F.
1588 if case .int(let x) = a, case .int(let y) = b, x >= 0, y > 0 { return .int(x % y) }
1589 let q = try floorOf(try divide(a, b, fractions: modes.preferFractions))
1590 return try subtract(a, try multiply(b, q))
1591 }
1592
1593 /// `calcFunc-idiv`: the quotient rounded down.
1594 func idiv(_ a: Value, _ b: Value) throws -> Value {
1595 if case .int(let x) = a, case .int(let y) = b {
1596 guard y != 0 else { throw Unsupported("division by zero") }
1597 let q = x / y
1598 return .int(q * y != x && (x < 0) != (y < 0) ? q - 1 : q)
1599 }
1600 return try floorOf(try divide(a, b))
1601 }
1602
1603 func floorOf(_ v: Value) throws -> Value {
1604 if case .int = v { return v }
1605 if case .frac(let n, let d) = v { return .int(n / d - (n % d < 0 ? 1 : 0)) }
1606 if case .float(let m, let e) = v {
1607 if e >= 0 {
1608 guard e <= 18 else { throw Unsupported("integer size") }
1609 let (i, overflow) = m.multipliedReportingOverflow(by: Int(try power10(e)))
1610 if overflow { throw Unsupported("integer size") }
1611 return .int(i)
1612 }
1613 guard -e <= 18 else { return .int(m < 0 ? -1 : 0) }
1614 let d = Int(try power10(-e))
1615 return .int(m / d - (m % d < 0 ? 1 : 0))
1616 }
1617 guard let i = Int(exactly: try double(v).rounded(.down)) else { throw Unsupported("integer size") }
1618 return .int(i)
1619 }
1620
1621 /// `math-covariance` of numbers without error forms: the variance of `xs` without `ys`,
1622 /// with `correlation` the correlation coefficient.
1623 func covariance(_ xs: [Value], _ ys: [Value]? = nil, population: Bool, correlation: Bool = false) throws -> Value {
1624 let n = xs.count
1625 guard n > 0 else { throw Unsupported("empty vector") }
1626 guard population || n > 1 else { throw Unsupported(ys == nil ? "variance of one value" : "arguments") }
1627 guard (ys ?? xs).count == n else { throw Unsupported("arguments") }
1628 return try extra(2) {
1629 func sum(_ v: [Value]) throws -> Value { try v.dropFirst().reduce(v[0], add) }
1630 func deviations(_ v: [Value]) throws -> [Value] {
1631 let shift = try divide(try sum(v), .int(-n), fractions: modes.preferFractions)
1632 return try v.map { try add($0, shift) }
1633 }
1634 let dx = try deviations(xs)
1635 let dy = try ys.map(deviations) ?? dx
1636 let products = try sum(try zip(dx, dy).map(multiply))
1637 let divisor = correlation
1638 ? try squareRoot(try multiply(try sum(try dx.map { try multiply($0, $0) }), try sum(try dy.map { try multiply($0, $0) })))
1639 : .int(population ? n : n - 1)
1640 return try divide(products, divisor, fractions: modes.preferFractions)
1641 }
1642 }
1643
1644 /// `math-flatten-many-vecs`: the arguments, vectors flattened into their elements.
1645 func elements(_ args: [Value]) throws -> [Value] {
1646 var items: [Value] = []
1647 for arg in args {
1648 if case .vector(let inner) = arg { items += try elements(inner) } else { items.append(arg) }
1649 }
1650 return items
1651 }
1652
1653 func one(_ args: [Value]) throws -> Value {
1654 guard args.count == 1 else { throw Unsupported("arguments") }
1655 if case .vector = args[0] { throw Unsupported("vector argument") }
1656 return args[0]
1657 }
1658
1659 /// An integer argument, from an integer or a float with an integer value
1660 /// (`math-messy-integerp`).
1661 func integer(_ v: Value) throws -> Int {
1662 guard isWhole(v) else { throw Unsupported("arguments") }
1663 return try trunc(v)
1664 }
1665
1666 /// The local date and time `now()` reads.
1667 func clock() -> DateComponents {
1668 var calendar = Calendar(identifier: .gregorian)
1669 calendar.timeZone = modes.timeZone
1670 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date())
1671 }
1672
1673
1674 func call(_ name: String, _ args: [Value]) throws -> Value {
1675 switch name {
1676 case "vsum":
1677 return try extra(2) { try elements(args).reduce(Value.int(0)) { try add($0, $1) } }
1678 case "vprod":
1679 return try extra(2) { try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } }
1680 case "vcount":
1681 return .int(try elements(args).count)
1682 case "vmean":
1683 let items = try elements(args)
1684 guard !items.isEmpty else { throw Unsupported("empty vector") }
1685 return try extra(2) { try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) }
1686 case "vmax", "vmin":
1687 // `math-reduce-many-vecs` compares at two digits more.
1688 let items = try elements(args)
1689 guard let first = items.first else { throw Unsupported("empty vector") }
1690 return try extra(2) {
1691 var best = first
1692 for item in items.dropFirst() {
1693 let order = try compare(item, best)
1694 if name == "vmax" ? order > 0 : order < 0 { best = item }
1695 }
1696 return best
1697 }
1698 case "vmedian":
1699 var items = try elements(args)
1700 guard !items.isEmpty else { throw Unsupported("empty vector") }
1701 // Calc leaves the median of dates unevaluated.
1702 if items.contains(where: { if case .date = $0 { true } else { false } }) { throw Unsupported("arguments") }
1703 try items.sort { try compare($0, $1) < 0 }
1704 if items.count % 2 == 1 { return items[items.count / 2] }
1705 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2), fractions: modes.preferFractions)
1706 case "vvar", "vpvar", "vsdev", "vpsdev":
1707 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
1708 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance
1709 case "mod":
1710 guard args.count == 2 else { throw Unsupported("arguments") }
1711 return try mod(args[0], args[1])
1712 case "idiv":
1713 guard args.count == 2 else { throw Unsupported("arguments") }
1714 return try idiv(args[0], args[1])
1715 case "fact", "dfact":
1716 // A float with an integer value gives a float, up to 20.
1717 let x = try one(args)
1718 guard isWhole(x), case let n = try trunc(x), n >= 0, x == .int(n) || (name == "fact" && n <= 20) else { throw Unsupported("arguments") }
1719 var result = Value.int(1)
1720 for k in stride(from: name == "fact" ? 2 : 2 + n % 2, through: n, by: name == "fact" ? 1 : 2) { result = try multiply(result, .int(k)) }
1721 return x == .int(n) ? result : try float(result)
1722 case "max", "min":
1723 guard !args.isEmpty else { throw Unsupported("arguments") }
1724 var best = args[0]
1725 for item in args.dropFirst() {
1726 let order = try compare(item, best)
1727 if name == "max" ? order > 0 : order < 0 { best = item }
1728 }
1729 return best
1730 case "abs":
1731 let x = try one(args)
1732 if case .date(let d) = x {
1733 // Calc leaves abs of day number 0 unevaluated.
1734 if d == .int(0) { throw Unsupported("date arithmetic") }
1735 return .date(try compare(d, .int(0)) < 0 ? try negate(d) : d)
1736 }
1737 return try compare(x, .int(0)) < 0 ? try negate(x) : x
1738 case "floor", "ceil", "trunc":
1739 if args.count == 1, case .date(let d) = args[0] { return .date(try call(name, [d])) }
1740 var x = try one(args)
1741 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1742 if case .int = x { return x }
1743 let d = try double(x)
1744 let r = name == "floor" ? d.rounded(.down) : name == "ceil" ? d.rounded(.up) : d.rounded(.towardZero)
1745 guard let i = Int(exactly: r) else { throw Unsupported("integer size") }
1746 return .int(i)
1747 case "round":
1748 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1749 if case .date(let d) = args[0] {
1750 guard args.count == 1 else { throw Unsupported("arguments") }
1751 return .date(try call(name, [d]))
1752 }
1753 var x = args[0]
1754 if args.count == 2 {
1755 // As `rounde`: scaled to an integer with fractions, then scaled back.
1756 guard isWhole(args[1]), case let places = try trunc(args[1]) else { throw Unsupported("arguments") }
1757 _ = try sign(x)
1758 if places <= 0, case .int = x { return x }
1759 let rounded = try round(try scale(x, places, fractions: true), even: false, away: true)
1760 return try scale(rounded, -places, fractions: modes.preferFractions)
1761 }
1762 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1763 guard case .float(let m, let e) = x else { return x }
1764 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") }
1765 return .int(i)
1766 case "sqrt":
1767 return try squareRoot(try one(args))
1768 case "exp":
1769 let x = try one(args)
1770 if x == .int(0) { return .int(1) }
1771 return try extra(2) { try expRaw(try float(x)) }
1772 case "ln":
1773 let x = try one(args)
1774 if x == .int(1) { return .int(0) }
1775 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
1776 return try extra(2) { try lnRaw(try float(x)) }
1777 case "log10":
1778 let x = try one(args)
1779 if case .int(let i) = x, i > 0 {
1780 var n = i
1781 var k = 0
1782 while n % 10 == 0 {
1783 n /= 10
1784 k += 1
1785 }
1786 if n == 1 { return .int(k) }
1787 }
1788 if case .frac(1, let d) = x, case (true, let k) = try integerLog(.int(d), .int(10)) { return .int(-k) }
1789 if isZero(x) { throw Unsupported("logarithm domain") }
1790 return try extra(2) {
1791 guard case .float(let m, let e) = try float(x), m > 0 else { throw Unsupported("logarithm domain") }
1792 if m == 1 { return try float(.int(e)) }
1793 let digits = digits(Int128(m)) - 1
1794 return try add(try divide(try lnRaw2(.float(m, -digits)), try ln10()), try float(.int(e + digits)))
1795 }
1796 case "sin", "cos", "tan":
1797 let x = try one(args)
1798 if x == .nan { return x }
1799 if case .int(let i) = x, modes.degrees ? i % (name == "tan" ? 180 : 90) == 0 : i == 0 {
1800 if name == "tan" { return .int(0) }
1801 // `(aref [0 1 0 -1] (math-mod (/ x 90) 4))`: a float quotient in math-mod can put
1802 // the index out of range, and Calc then leaves the call alone.
1803 guard case .int(let quarter) = try mod(.int(i / 90), .int(4)), (0...3).contains(quarter) else {
1804 throw Unsupported("number size")
1805 }
1806 return .int((name == "sin" ? [0, 1, 0, -1] : [1, 0, -1, 0])[quarter])
1807 }
1808 return try extra(2) {
1809 let r = try float(x)
1810 let radians = modes.degrees ? try multiply(r, try piOver180()) : r
1811 if name == "sin" { return try sinRaw(radians) }
1812 if name == "cos" { return try cosRaw(radians) }
1813 let cosine = try cosRaw(radians)
1814 // Calc leaves the quotient by zero alone.
1815 if isZero(cosine) { throw Unsupported("division by zero") }
1816 return try divide(try sinRaw(radians), cosine)
1817 }
1818 case "arcsin", "arccos", "arctan":
1819 let x = try one(args)
1820 if modes.degrees, case .int(let i) = x {
1821 switch (name, i) {
1822 case ("arcsin", -1), ("arcsin", 1): return .int(90 * i)
1823 case ("arccos", -1), ("arccos", 0): return .int(90 - 90 * i)
1824 case ("arctan", -1), ("arctan", 1): return .int(45 * i)
1825 default: break
1826 }
1827 }
1828 if x == .int(name == "arccos" ? 1 : 0) { return .int(0) }
1829 if x == .nan { return x }
1830 return try extra(2) {
1831 let r = try float(x)
1832 let angle = name == "arcsin" ? try arcsinRaw(r) : name == "arccos" ? try subtract(try piOver2(), try arcsinRaw(r)) : try arctanRaw(r)
1833 return modes.degrees ? try divide(angle, try piOver180()) : angle
1834 }
1835 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor":
1836 guard args.count == 2 else { throw Unsupported("arguments") }
1837 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"]
1838 return try binary(ops[name]!, args[0], args[1])
1839 case "lnot":
1840 return .int(try truth(try one(args)) ? 0 : 1)
1841 case "percent":
1842 let x = try one(args)
1843 _ = try sign(x)
1844 return try divide(x, .int(100))
1845 case "float", "pfloat":
1846 return try float(try one(args))
1847 case "sign":
1848 return .int(try sign(try one(args)))
1849 case "rounde", "roundu":
1850 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1851 let x = args[0]
1852 _ = try sign(x)
1853 guard args.count == 2 else { return try round(x, even: name == "rounde") }
1854 guard isWhole(args[1]), case let places = try trunc(args[1]) else { throw Unsupported("arguments") }
1855 if places <= 0, case .int = x { return x }
1856 let rounded = try round(try scale(x, places, fractions: true), even: name == "rounde")
1857 return try scale(rounded, -places, fractions: modes.preferFractions)
1858 case "frac":
1859 return try toFraction(try one(args))
1860 case "fdiv":
1861 guard args.count == 2 else { throw Unsupported("arguments") }
1862 func parts(_ v: Value) throws -> (Int, Int) {
1863 if isWhole(v) { return (try trunc(v), 1) }
1864 guard case .frac(let n, let d) = v else { throw Unsupported("arguments") }
1865 return (n, d)
1866 }
1867 let (n1, d1) = try parts(args[0])
1868 let (n2, d2) = try parts(args[1])
1869 guard n2 != 0 else { throw Unsupported("division by zero") }
1870 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
1871 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
1872 if o1 || o2 { throw Unsupported("integer size") }
1873 return try fraction(n, d)
1874 case "gcd":
1875 guard args.count == 2 else { throw Unsupported("arguments") }
1876 return try gcd(args[0], args[1])
1877 case "lcm":
1878 guard args.count == 2 else { throw Unsupported("arguments") }
1879 return try divide(try absolute(try multiply(args[0], args[1])), try gcd(args[0], args[1]), fractions: modes.preferFractions)
1880 case "choose", "perm":
1881 guard args.count == 2, case .int(let n) = args[0], case .int(let m) = args[1] else { throw Unsupported("arguments") }
1882 if name == "choose" { return .int(try choose(n, m)) }
1883 guard m >= 0, m <= n else { throw Unsupported("arguments") }
1884 var result = Value.int(1)
1885 for k in stride(from: n - m + 1, through: n, by: 1) { result = try multiply(result, .int(k)) }
1886 return result
1887 case "pow":
1888 guard args.count == 2 else { throw Unsupported("arguments") }
1889 return try power(args[0], args[1], fractions: modes.preferFractions)
1890 case "exp10":
1891 let x = try one(args)
1892 guard case .int(let n) = x else { throw Unsupported("arguments") }
1893 return n == 0 ? .int(1) : try makeFloat(1, n)
1894 case "nroot":
1895 guard args.count == 2, case .int(let n) = args[1], n >= 1 else { throw Unsupported("arguments") }
1896 _ = try sign(args[0])
1897 return n == 1 ? args[0] : try rootPower(args[0], n)
1898 case "hypot":
1899 guard args.count == 2 else { throw Unsupported("arguments") }
1900 let (a, b) = (args[0], args[1])
1901 _ = (try sign(a), try sign(b))
1902 if isZero(a) { return try absolute(b) }
1903 if isZero(b) { return try absolute(a) }
1904 return try extra(1) { try squareRoot(try add(try multiply(a, a), try multiply(b, b))) }
1905 case "log":
1906 guard args.count == 2 else {
1907 guard args.count == 1 else { throw Unsupported("arguments") }
1908 return try call("ln", args)
1909 }
1910 let (x, b) = (args[0], args[1])
1911 _ = (try sign(x), try sign(b))
1912 if b == .int(10) || b == .float(1, 1) { return try call("log10", [x]) }
1913 if isZero(x) || isZero(b) || b == .int(1) || b == .float(1, 0) { throw Unsupported("logarithm domain") }
1914 if x == .int(1) || x == .float(1, 0) {
1915 if case .float = b { return .float(0, 0) }
1916 return .int(0)
1917 }
1918 if rational(x) != nil, rational(b) != nil, try sign(x) > 0, try sign(b) > 0 {
1919 var sign = 1
1920 var (xx, bb) = (x, b)
1921 if try compare(.int(1), x) >= 0 {
1922 sign = -1
1923 xx = try divide(.int(1), x)
1924 }
1925 if try compare(.int(1), b) >= 0 {
1926 sign = -sign
1927 bb = try divide(.int(1), b)
1928 }
1929 let inverse = try compare(xx, bb) < 0
1930 let (exact, n) = inverse ? try integerLog(bb, xx) : try integerLog(xx, bb)
1931 if exact { return inverse ? try divide(.int(1), .int(sign * n), fractions: modes.preferFractions) : .int(sign * n) }
1932 }
1933 return try extra(2) { try divide(try lnRaw(try float(x)), try lnRaw(try float(b))) }
1934 case "sinh", "cosh":
1935 let x = try one(args)
1936 if x == .int(0) { return .int(name == "sinh" ? 0 : 1) }
1937 _ = try sign(x)
1938 return try extra(2) {
1939 let e = try expRaw(try float(x))
1940 return try multiply(try add(e, try divide(.int(name == "sinh" ? -1 : 1), e)), .float(5, -1))
1941 }
1942 case "tanh":
1943 let x = try one(args)
1944 if x == .int(0) { return x }
1945 _ = try sign(x)
1946 return try extra(2) {
1947 let f = try float(x)
1948 let e = try extra(2) { try expRaw(f) }
1949 let inverse = try divide(.int(1), e)
1950 return try divide(try subtract(e, inverse), try add(e, inverse))
1951 }
1952 case "arcsinh":
1953 let x = try one(args)
1954 if x == .int(0) { return x }
1955 _ = try sign(x)
1956 return try extra(2) { try lnRaw(try add(x, try squareRootRaw(try add(try multiply(x, x), .float(1, 0))))) }
1957 case "arccosh":
1958 let x = try one(args)
1959 if x == .int(1) { return .int(0) }
1960 guard try compare(x, .int(-1)) != 0 else { throw Unsupported("complex result") }
1961 return try extra(2) {
1962 let xp1 = try add(.int(1), x)
1963 return try lnRaw(try add(x, try multiply(xp1, try squareRootRaw(try divide(try subtract(x, .float(1, 0)), xp1)))))
1964 }
1965 case "arctanh":
1966 let x = try one(args)
1967 if x == .int(0) { return x }
1968 guard try compare(x, .int(1)) <= 0 else { throw Unsupported("complex result") }
1969 return try extra(2) {
1970 try multiply(try lnRaw(try divide(try add(.float(1, 0), x), try subtract(.int(1), x))), .float(5, -1))
1971 }
1972 case "arctan2":
1973 guard args.count == 2 else { throw Unsupported("arguments") }
1974 _ = (try sign(args[0]), try sign(args[1]))
1975 return try extra(2) {
1976 let r = try arctan2Raw(try float(args[0]), try float(args[1]))
1977 return modes.degrees ? try divide(r, try piOver180()) : r
1978 }
1979 case "deg", "rad":
1980 let x = try one(args)
1981 _ = try sign(x)
1982 return try extra(2) { name == "deg" ? try divide(x, try piOver180()) : try multiply(x, try piOver180()) }
1983 case "vflat":
1984 return .vector(try elements(args))
1985 case "vgmean", "vhmean":
1986 let items = try elements(args)
1987 guard !items.isEmpty else { throw Unsupported("empty vector") }
1988 // Calc's root of one float, a power of 1:1, stays unevaluated.
1989 if name == "vgmean", items.count == 1, case .float = items[0] { throw Unsupported("arguments") }
1990 return try extra(2) {
1991 if name == "vhmean" {
1992 let inverses = try items.map { try divide(.int(1), $0, fractions: modes.preferFractions) }
1993 return try divide(.int(items.count), try inverses.dropFirst().reduce(inverses[0], add), fractions: modes.preferFractions)
1994 }
1995 let product = try items.dropFirst().reduce(items[0], multiply)
1996 return items.count == 2 ? try squareRoot(product) : try rootPower(product, items.count)
1997 }
1998 case "vcov", "vpcov", "vcorr":
1999 // Two vectors; one matrix argument isn't supported.
2000 guard args.count == 2 else { throw Unsupported("arguments") }
2001 return try covariance(try elements([args[0]]), try elements([args[1]]), population: name == "vpcov", correlation: name == "vcorr")
2002 case "agmean":
2003 guard args.count == 2 else { throw Unsupported("arguments") }
2004 let (a, b) = (args[0], args[1])
2005 _ = (try sign(a), try sign(b))
2006 if try compare(a, b) == 0 || isZero(a) { return a }
2007 if isZero(b) { return b }
2008 return try extra(2) {
2009 var (x, y) = (try float(try absolute(a)), try float(try absolute(b)))
2010 for _ in 0..<1000 {
2011 if nearlyEqual(x, y) { return x }
2012 let mean = try multiply(try add(x, y), .float(5, -1))
2013 y = try extra(1) { try squareRootRaw(try multiply(x, y)) }
2014 x = mean
2015 }
2016 throw Unsupported("number")
2017 }
2018 case "now":
2019 guard args.isEmpty else { throw Unsupported("arguments") }
2020 let c = clock()
2021 return try dateValue(c.year!, c.month!, c.day!, (c.hour!, c.minute!, c.second!))
2022 case "date":
2023 // `date(d)` converts between a date and its day number; otherwise the
2024 // arguments are [year,] month, day[, hour[, minute[, second]]].
2025 if args.count == 1 {
2026 if case .date(let d) = args[0] { return d }
2027 return .date(try dayNumber(args[0]))
2028 }
2029 guard (2...6).contains(args.count) else { throw Unsupported("arguments") }
2030 let n = try args.map(integer)
2031 if n.count == 2 { return try dateValue(clock().year!, n[0], n[1]) }
2032 return try dateValue(n[0], n[1], n[2], n.count > 3 ? (n[3], n.count > 4 ? n[4] : 0, n.count > 5 ? n[5] : 0) : nil)
2033 case "year", "month", "day", "hour", "minute", "second", "yearday":
2034 let dt = try dateParts(try one(args))
2035 switch name {
2036 case "year": return .int(dt.year)
2037 case "month": return .int(dt.month)
2038 case "day": return .int(dt.day)
2039 case "hour": return .int(dt.time?.hour ?? 0)
2040 case "minute": return .int(dt.time?.minute ?? 0)
2041 case "second": return .int(dt.time?.second ?? 0)
2042 default: return .int(try absolute(dt.year, dt.month, dt.day) - absolute(dt.year, 1, 1) + 1)
2043 }
2044 case "weekday":
2045 return .int(Days.weekday(try floorInt(try dayNumber(try one(args)))))
2046 case "newweek":
2047 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
2048 let day = try floorInt(try dayNumber(args[0]))
2049 let weekday = args.count > 1 ? try integer(args[1]) : 0
2050 guard (0...6).contains(weekday) else { throw Unsupported("arguments") }
2051 return .date(.int(day - Days.weekday(day - weekday)))
2052 case "newmonth":
2053 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
2054 var day = args.count > 1 ? try integer(args[1]) : 1
2055 guard (0...31).contains(day) else { throw Unsupported("arguments") }
2056 let dt = try dateParts(args[0])
2057 let days = try daysInMonth(dt.year, dt.month)
2058 day = day == 0 || day > days ? days - 1 : day - 1
2059 return .date(.int(try absolute(dt.year, dt.month, 1) + day))
2060 case "newyear":
2061 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
2062 var day = args.count > 1 ? try integer(args[1]) : 1
2063 let dt = try dateParts(args[0])
2064 if (-12 ... -1).contains(day) { return .date(.int(try absolute(dt.year, -day, 1))) }
2065 guard (0...366).contains(day) else { throw Unsupported("arguments") }
2066 let days = try daysInMonth(dt.year, 2) == 29 ? 366 : 365
2067 if day == 0 || day > days { day = days }
2068 return .date(.int(try absolute(dt.year, 1, 1) + day - 1))
2069 case "incmonth", "incyear":
2070 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
2071 let step = args.count > 1 ? args[1] : .int(1)
2072 let months = try integer(name == "incyear" ? try multiply(step, .int(12)) : step)
2073 guard abs(months) < 1_000_000_000 else { throw Unsupported("arguments") }
2074 let dt = try dateParts(args[0])
2075 let m = dt.month - 1 + months
2076 let extra = m >= 0 ? m / 12 : (m - 11) / 12
2077 let month = m - extra * 12 + 1
2078 var year = dt.year + extra
2079 let day = min(dt.day, try daysInMonth(year, month))
2080 // Past the year zero, which Calc doesn't have.
2081 if dt.year > 0, year <= 0 { year -= 1 }
2082 if dt.year < 0, year >= 0 { year += 1 }
2083 return try dateValue(year, month, day, dt.time)
2084 case "badd", "bsub":
2085 guard args.count == 2 else { throw Unsupported("arguments") }
2086 var (a, b) = (args[0], args[1])
2087 if name == "bsub" {
2088 guard case .date = a else { throw Unsupported("arguments") }
2089 if case .date = b {
2090 if try compare(a, b) < 0 { return try negate(try call(name, [b, a])) }
2091 let (x, xHoliday) = try toBusinessDay(a)
2092 let (y, yHoliday) = try toBusinessDay(b)
2093 return try add(try subtract(x, y), .int(yHoliday && !xHoliday ? 1 : 0))
2094 }
2095 b = try negate(b)
2096 }
2097 if case .date = b {
2098 if case .date = a { throw Unsupported("arguments") }
2099 (a, b) = (b, a)
2100 }
2101 guard case .date = a else { throw Unsupported("arguments") }
2102 if try sign(b) == 0 { return a }
2103 let (day, holiday) = try toBusinessDay(a)
2104 return try fromBusinessDay(try add(day, holiday && sign(b) > 0 ? try subtract(b, .int(1)) : b))
2105 case "julian":
2106 // `math-julian-date-beginning`: 1721424.5 days before day 0.
2107 let x = try one(args)
2108 if case .date(let d) = x {
2109 if case .int = d { return try add(d, .int(1721425)) }
2110 return try add(d, try add(.float(17214245, -1), try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
2111 }
2112 if case .int(let d) = x { return .date(try add(.int(d), .int(-1721425))) }
2113 let shifted = try subtract(try dayNumber(x), .float(17214245, -1))
2114 return .date(try subtract(shifted, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
2115 case "unixtime":
2116 // `math-unix-epoch`: day 719163.
2117 let x = try one(args)
2118 if case .date(let d) = x {
2119 guard precision <= 12 else { throw Unsupported("calc precision") }
2120 let seconds = try round(try multiply(try subtract(d, .int(719163)), .int(86400)), even: false)
2121 return try add(seconds, .int(try zoneOffset(modes.timeZone)))
2122 }
2123 let day = try add(.int(719163), try divide(try dayNumber(x), .float(864, 2)))
2124 return .date(try subtract(day, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
2125 default:
2126 throw Unsupported("function \(name)")
2127 }
2128 }
2129 }
2130}