Commit 490d888f78

490d888f783994a7619142899a89f5372d5b15ff

parent: ec476b23d8

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 18:56 UTC

Reduce trig arguments as Calc does before the native function

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +152 −47
@@ -116,6 +116,8 @@ public enum Calc {
116 // Constants to 36 digits, rounded to the precision, as `math-defcache` gives them. 116 // Constants to 36 digits, rounded to the precision, as `math-defcache` gives them.
117 static func pi() throws -> Value { try makeFloat(314159265358979323846264338327950288, -35) } 117 static func pi() throws -> Value { try makeFloat(314159265358979323846264338327950288, -35) }
118 static func piOver2() throws -> Value { try makeFloat(157079632679489661923132169163975144, -35) } 118 static func piOver2() throws -> Value { try makeFloat(157079632679489661923132169163975144, -35) }
119 static func piOver4() throws -> Value { try makeFloat(785398163397448309615660845819875721, -36) }
120 static func twoPi() throws -> Value { try makeFloat(628318530717958647692528676655900577, -35) }
119 static func piOver180() throws -> Value { try makeFloat(174532925199432957692369076848861271, -37) } 121 static func piOver180() throws -> Value { try makeFloat(174532925199432957692369076848861271, -37) }
120 122
121 /// `math-float`. 123 /// `math-float`.
@@ -277,19 +279,6 @@ public enum Calc {
277 } 279 }
278 } 280 }
279 281
280 static func fromDouble(_ d: Double) throws -> Value {
281 // Calc works these out at two digits more; past 16 it uses its own series.
282 guard precision <= 14 else { throw Unsupported("calc precision") }
283 guard d.isFinite else { throw Unsupported("infinite result") }
284 if d == 0 { return .float(0, 0) }
285 // Seventeen significant digits are exact for a Double; rounding to 12 follows.
286 let text = String(format: "%.16e", d)
287 let pieces = text.split(separator: "e")
288 let digitsText = pieces[0].replacingOccurrences(of: ".", with: "")
289 guard let mantissa = Int128(digitsText), let exponent = Int(pieces[1]) else { throw Unsupported("number") }
290 return try makeFloat(mantissa, exponent - 16)
291 }
292
293 static func isSymbolic(_ vs: Value...) -> Bool { 282 static func isSymbolic(_ vs: Value...) -> Bool {
294 vs.contains { if case .symbolic = $0 { true } else { false } } 283 vs.contains { if case .symbolic = $0 { true } else { false } }
295 } 284 }
@@ -324,10 +313,22 @@ public enum Calc {
324 let ediff = e1 - e2 313 let ediff = e1 - e2
325 if ediff >= 0 { 314 if ediff >= 0 {
326 if ediff >= 2 * precision { return try makeFloat(m1, e1) } 315 if ediff >= 2 * precision { return try makeFloat(m1, e1) }
327 return try makeFloat(try scaleRounding(m1, ediff) + m2, e2) 316 let (m, shift) = try align(m1, ediff, m2)
317 return try makeFloat(m, e2 + shift)
328 } 318 }
329 if -ediff >= 2 * precision { return try makeFloat(m2, e2) } 319 if -ediff >= 2 * precision { return try makeFloat(m2, e2) }
330 return try makeFloat(m1 + (try scaleRounding(m2, -ediff)), e1) 320 let (m, shift) = try align(m2, -ediff, m1)
321 return try makeFloat(m, e1 + shift)
322 }
323
324 /// `big` times 10^ediff plus `small`, and the power of ten that scales it. Past 37 digits
325 /// the digits of `small` below the precision become one sticky digit, which rounds the same.
326 static func align(_ big: Int128, _ ediff: Int, _ small: Int128) throws -> (Int128, Int) {
327 if digits(big) + ediff <= 37 { return (try scaleRounding(big, ediff) + small, 0) }
328 let s = max(precision + 2 - digits(big), 0)
329 let k = ediff - s
330 let (q, r) = k > 37 ? (0, small) : small.quotientAndRemainder(dividingBy: try power10(k))
331 return (try scaleRounding(big, s + 1) + q * 10 + r.signum(), k - 1)
331 } 332 }
332 333
333 static func negate(_ a: Value) throws -> Value { 334 static func negate(_ a: Value) throws -> Value {
@@ -507,7 +508,22 @@ public enum Calc {
507 static func squareRootRaw(_ a: Value) throws -> Value { 508 static func squareRootRaw(_ a: Value) throws -> Value {
508 if isZero(a) { return a } 509 if isZero(a) { return a }
509 guard try sign(a) > 0 else { throw Unsupported("complex result") } 510 guard try sign(a) > 0 else { throw Unsupported("complex result") }
510 return try emacs({ $0.squareRoot() }, a) 511 if precision <= 16 { return try emacs({ $0.squareRoot() }, a) }
512 // Newton's method from the root of the first six or seven digits.
513 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
514 var ldiff = digits(Int128(m)) - 6
515 if (e + ldiff) % 2 != 0 { ldiff += 1 }
516 let head = ldiff >= 0 ? Int128(m) / (try power10(ldiff)) : Int128(m) * (try power10(-ldiff))
517 var root = Int128(Double(head).squareRoot())
518 while root * root > head { root -= 1 }
519 while (root + 1) * (root + 1) <= head { root += 1 }
520 var guess = try makeFloat(root, (e + ldiff) / 2)
521 for _ in 0..<1000 {
522 let next = try multiply(try add(guess, try divide(a, guess)), .float(5, -1))
523 if nearlyEqual(next, guess) { return next }
524 guess = next
525 }
526 throw Unsupported("number")
511 } 527 }
512 528
513 /// `math-exp-raw` of a float. 529 /// `math-exp-raw` of a float.
@@ -525,7 +541,100 @@ public enum Calc {
525 /// `math-arctan-raw` of a float. 541 /// `math-arctan-raw` of a float.
526 static func arctanRaw(_ x: Value) throws -> Value { 542 static func arctanRaw(_ x: Value) throws -> Value {
527 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) } 543 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) }
528 return isZero(x) ? x : try emacs({ Foundation.atan($0) }, x) 544 if isZero(x) { return x }
545 if precision <= 16 { return try emacs({ Foundation.atan($0) }, x) }
546 if symbolicMode { throw Unsupported("symbolic mode") }
547 if x == .float(1, 0) { return try piOver4() }
548 if try compare(.float(414214, -6), x) < 0 {
549 if try compare(.float(1, 0), x) < 0 {
550 return try subtract(try multiply(try pi(), .float(5, -1)), try arctanRaw(try divide(.float(1, 0), x)))
551 }
552 let reduced = try divide(try subtract(.float(1, 0), x), try add(.float(1, 0), x))
553 return try subtract(try multiply(try pi(), .float(25, -2)), try arctanRaw(reduced))
554 }
555 // `math-arctan-series`.
556 let xnegsqr = try negate(try multiply(x, x))
557 var (sum, power, n) = (x, x, 3)
558 for _ in 0..<10000 {
559 power = try multiply(power, xnegsqr)
560 let next = try add(sum, try divide(power, try float(.int(n))))
561 if nearlyEqual(sum, next) { return sum }
562 (sum, n) = (next, n + 2)
563 }
564 throw Unsupported("number")
565 }
566
567 /// `math-arctan2-raw` of floats.
568 static func arctan2Raw(_ y: Value, _ x: Value) throws -> Value {
569 if isZero(y) { return try sign(x) < 0 ? try pi() : .float(0, 0) }
570 if isZero(x) { return try sign(y) > 0 ? try piOver2() : try negate(try piOver2()) }
571 if try sign(x) > 0 { return try arctanRaw(try divide(y, x)) }
572 if try sign(y) > 0 { return try add(try arctanRaw(try divide(y, x)), try pi()) }
573 // `math-sub-float` gives pi itself, not its negative, when the angle is too small to count.
574 let angle = try arctanRaw(try divide(y, x))
575 if case .float(_, let e) = angle, case .float(_, let ep) = try pi(), ep - e >= 2 * precision { return try pi() }
576 return try subtract(angle, try pi())
577 }
578
579 /// `math-arcsin-raw` of a real float.
580 static func arcsinRaw(_ x: Value) throws -> Value {
581 try arctan2Raw(x, try squareRootRaw(try subtract(.float(1, 0), try multiply(x, x))))
582 }
583
584 /// `math-sin-raw` of a real float; `orgx` is the argument before reduction.
585 static func sinRaw(_ x: Value, _ orgx: Value? = nil) throws -> Value {
586 let orgx = orgx ?? x
587 if try sign(x) < 0 { return try negate(try sinRaw(try negate(x), orgx)) }
588 if try compare(.float(7, 0), x) < 0 {
589 // `math-mod` by 2 pi.
590 let turns = try floorInt(try divide(x, try twoPi()))
591 return try sinRaw(try subtract(x, try multiply(.int(turns), try twoPi())), orgx)
592 }
593 return try sinRaw2(x, orgx)
594 }
595
596 /// `math-cos-raw` of a real float.
597 static func cosRaw(_ x: Value) throws -> Value {
598 try sinRaw(try subtract(try piOver2(), x), x)
599 }
600
601 /// `math-nearly-zerop-float`: `a` is zero next to `b`, at one digit less.
602 static func nearlyZero(_ a: Value, _ b: Value) -> Bool {
603 guard case .float(let ma, let ea) = a, case .float(let mb, let eb) = b else { return false }
604 return ma == 0 || digits(Int128(ma)) + ea <= 1 + (mb == 0 ? 0 : digits(Int128(mb))) + eb - (precision - 1)
605 }
606
607 /// `math-sin-raw-2`.
608 static func sinRaw2(_ x: Value, _ orgx: Value) throws -> Value {
609 let xmpo2 = try subtract(try piOver2(), x)
610 if try sign(xmpo2) < 0 { return try negate(try sinRaw2(try subtract(x, try pi()), orgx)) }
611 if try compare(try piOver4(), x) < 0 { return try cosRaw2(xmpo2, orgx) }
612 if try compare(x, try negate(try piOver4())) < 0 { return try negate(try cosRaw2(try add(try piOver2(), x), orgx)) }
613 if nearlyZero(x, orgx) { return .float(0, 0) }
614 if precision <= 16 { return try emacs({ Foundation.sin($0) }, x) }
615 if symbolicMode { throw Unsupported("symbolic mode") }
616 return try sinSeries(x, 6, 4, x, try negate(try multiply(x, x)))
617 }
618
619 /// `math-cos-raw-2`.
620 static func cosRaw2(_ x: Value, _ orgx: Value) throws -> Value {
621 if nearlyZero(x, orgx) { return .float(1, 0) }
622 if precision <= 16 { return try emacs({ Foundation.cos($0) }, x) }
623 if symbolicMode { throw Unsupported("symbolic mode") }
624 let xnegsqr = try negate(try multiply(x, x))
625 return try sinSeries(try add(.float(1, 0), try multiply(xnegsqr, .float(5, -1))), 24, 5, xnegsqr, xnegsqr)
626 }
627
628 /// `math-sin-series`.
629 static func sinSeries(_ sum: Value, _ nfac: Int, _ n: Int, _ x: Value, _ xnegsqr: Value) throws -> Value {
630 var (sum, nfac, n, x) = (sum, Value.int(nfac), n, x)
631 for _ in 0..<10000 {
632 x = try multiply(x, xnegsqr)
633 let next = try add(sum, try divide(x, try float(nfac)))
634 if nearlyEqual(sum, next) { return sum }
635 (sum, nfac, n) = (next, try multiply(nfac, .int(n * (n + 1))), n + 2)
636 }
637 throw Unsupported("number")
529 } 638 }
530 639
531 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) } 640 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) }
@@ -1456,8 +1565,6 @@ public enum Calc {
1456 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date()) 1565 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date())
1457 } 1566 }
1458 1567
1459 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x }
1460 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x }
1461 1568
1462 func call(_ name: String, _ args: [Value]) throws -> Value { 1569 func call(_ name: String, _ args: [Value]) throws -> Value {
1463 switch name { 1570 switch name {
@@ -1583,33 +1690,42 @@ public enum Calc {
1583 } 1690 }
1584 case "sin", "cos", "tan": 1691 case "sin", "cos", "tan":
1585 let x = try one(args) 1692 let x = try one(args)
1586 if modes.degrees, case .int(let i) = x, i % 90 == 0 { 1693 if x == .nan { return x }
1694 if case .int(let i) = x, modes.degrees ? i % (name == "tan" ? 180 : 90) == 0 : i == 0 {
1587 let quarter = ((i / 90) % 4 + 4) % 4 1695 let quarter = ((i / 90) % 4 + 4) % 4
1588 switch name { 1696 switch name {
1589 case "sin": return .int([0, 1, 0, -1][quarter]) 1697 case "sin": return .int([0, 1, 0, -1][quarter])
1590 case "cos": return .int([1, 0, -1, 0][quarter]) 1698 case "cos": return .int([1, 0, -1, 0][quarter])
1591 default: 1699 default: return .int(0)
1592 guard quarter % 2 == 0 else { throw Unsupported("infinite result") }
1593 return .int(0)
1594 } 1700 }
1595 } 1701 }
1596 if !modes.degrees, x == .int(0) { return .int(name == "cos" ? 1 : 0) } 1702 return try extra(2) {
1597 let r = radians(try double(x)) 1703 let r = try float(x)
1598 return try fromDouble(name == "sin" ? Foundation.sin(r) : name == "cos" ? Foundation.cos(r) : Foundation.tan(r)) 1704 let radians = modes.degrees ? try multiply(r, try piOver180()) : r
1705 if name == "sin" { return try sinRaw(radians) }
1706 if name == "cos" { return try cosRaw(radians) }
1707 let cosine = try cosRaw(radians)
1708 // Calc leaves the quotient by zero alone.
1709 if isZero(cosine) { throw Unsupported("division by zero") }
1710 return try divide(try sinRaw(radians), cosine)
1711 }
1599 case "arcsin", "arccos", "arctan": 1712 case "arcsin", "arccos", "arctan":
1600 let x = try one(args) 1713 let x = try one(args)
1601 if modes.degrees, case .int(let i) = x { 1714 if modes.degrees, case .int(let i) = x {
1602 switch (name, i) { 1715 switch (name, i) {
1603 case ("arcsin", -1), ("arcsin", 0), ("arcsin", 1): return .int(90 * i) 1716 case ("arcsin", -1), ("arcsin", 1): return .int(90 * i)
1604 case ("arccos", -1), ("arccos", 0), ("arccos", 1): return .int(90 - 90 * i) 1717 case ("arccos", -1), ("arccos", 0): return .int(90 - 90 * i)
1605 case ("arctan", -1), ("arctan", 0), ("arctan", 1): return .int(45 * i) 1718 case ("arctan", -1), ("arctan", 1): return .int(45 * i)
1606 default: break 1719 default: break
1607 } 1720 }
1608 } 1721 }
1609 let d = try double(x) 1722 if x == .int(name == "arccos" ? 1 : 0) { return .int(0) }
1610 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") } 1723 if x == .nan { return x }
1611 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d) 1724 return try extra(2) {
1612 return try fromDouble(angle(r)) 1725 let r = try float(x)
1726 let angle = name == "arcsin" ? try arcsinRaw(r) : name == "arccos" ? try subtract(try piOver2(), try arcsinRaw(r)) : try arctanRaw(r)
1727 return modes.degrees ? try divide(angle, try piOver180()) : angle
1728 }
1613 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor": 1729 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor":
1614 guard args.count == 2 else { throw Unsupported("arguments") } 1730 guard args.count == 2 else { throw Unsupported("arguments") }
1615 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"] 1731 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"]
@@ -1722,7 +1838,8 @@ public enum Calc {
1722 if x == .int(0) { return x } 1838 if x == .int(0) { return x }
1723 _ = try sign(x) 1839 _ = try sign(x)
1724 return try extra(2) { 1840 return try extra(2) {
1725 let e = try extra(2) { try expRaw(try float(x)) } 1841 let f = try float(x)
1842 let e = try extra(2) { try expRaw(f) }
1726 let inverse = try divide(.int(1), e) 1843 let inverse = try divide(.int(1), e)
1727 return try divide(try subtract(e, inverse), try add(e, inverse)) 1844 return try divide(try subtract(e, inverse), try add(e, inverse))
1728 } 1845 }
@@ -1750,19 +1867,7 @@ public enum Calc {
1750 guard args.count == 2 else { throw Unsupported("arguments") } 1867 guard args.count == 2 else { throw Unsupported("arguments") }
1751 _ = (try sign(args[0]), try sign(args[1])) 1868 _ = (try sign(args[0]), try sign(args[1]))
1752 return try extra(2) { 1869 return try extra(2) {
1753 let (y, x) = (try float(args[0]), try float(args[1])) 1870 let r = try arctan2Raw(try float(args[0]), try float(args[1]))
1754 let r: Value
1755 if isZero(y) {
1756 r = try sign(x) < 0 ? try pi() : .float(0, 0)
1757 } else if isZero(x) {
1758 r = try sign(y) > 0 ? try piOver2() : try negate(try piOver2())
1759 } else if try sign(x) > 0 {
1760 r = try arctanRaw(try divide(y, x))
1761 } else if try sign(y) > 0 {
1762 r = try add(try arctanRaw(try divide(y, x)), try pi())
1763 } else {
1764 r = try subtract(try arctanRaw(try divide(y, x)), try pi())
1765 }
1766 return modes.degrees ? try divide(r, try piOver180()) : r 1871 return modes.degrees ? try divide(r, try piOver180()) : r
1767 } 1872 }
1768 case "deg", "rad": 1873 case "deg", "rad":
Tests/OrgCoreTests/CalcNumericTests.swift added +74
@@ -0,0 +1,74 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct CalcNumericTests {
6 /// A random real number up to `scale` digits before the point: an integer, a fraction or
7 /// a float, tiny to large.
8 static func argument(_ generator: inout SystemRandomNumberGenerator, scale: Int = 6) -> String {
9 let sign = Bool.random(using: &generator) ? "-" : ""
10 let digits = Int.random(in: 1...9, using: &generator)
11 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(digits)
12 switch Int.random(in: 0..<5, using: &generator) {
13 case 0: return sign + String(Int.random(in: 0...(scale > 2 ? 720 : 70), using: &generator))
14 case 1: return sign + "\(Int.random(in: 1...99, using: &generator)):\(Int.random(in: 2...99, using: &generator))"
15 case 2: return sign + "\(mantissa)e\(Int.random(in: -30...(scale - mantissa.count), using: &generator))"
16 case 3: return sign + "\(mantissa)e\(Int.random(in: -mantissa.count - 1...(scale - mantissa.count), using: &generator))"
17 default: return sign + ["90.", "180.", "45", "30", "1.5707963267949", "3.14159265358979", "0.785398163397448", "1", "1.", "0.5",
18 "1e-10", "6.28318530717959", "7.", "7.00000000000001"].randomElement(using: &generator)!
19 }
20 }
21
22 /// A random number from -1 to 1.
23 static func unit(_ generator: inout SystemRandomNumberGenerator) -> String {
24 let sign = Bool.random(using: &generator) ? "-" : ""
25 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(Int.random(in: 1...9, using: &generator))
26 switch Int.random(in: 0..<4, using: &generator) {
27 case 0: return sign + ["0", "1", "1.", "0.5", "0.", "0.999999999999", "1e-10"].randomElement(using: &generator)!
28 case 1:
29 let d = Int.random(in: 2...99, using: &generator)
30 return sign + "\(Int.random(in: 1..<d, using: &generator)):\(d)"
31 case 2: return sign + "\(mantissa)e\(-mantissa.count - Int.random(in: 0...20, using: &generator))"
32 default: return sign + "0.\(mantissa)"
33 }
34 }
35
36 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
37 func trigonometryMatchesCalc() throws {
38 var generator = SystemRandomNumberGenerator()
39 for precision in [3, 6, 8, 12, 14, 15, 16, 17, 18] {
40 for radians in [false, true] {
41 var cases: [(String, String)] = ["sin(nan)", "cos(nan)", "arctan(nan)", "tan(180)", "tan(-360)", "tan(0)", "arcsin(0)",
42 "arccos(1)", "arccos(0)", "arcsin(-1)", "arctan(1)", "sqrt(2)", "sqrt(1e-9)"].map { ($0, "(float 0)") }
43 for _ in 0..<500 {
44 let f = ["sin", "cos", "tan", "arcsin", "arccos", "arctan", "arctan2", "sinh", "cosh", "tanh", "sqrt"].randomElement(using: &generator)!
45 let x = switch f {
46 case "arcsin", "arccos": Self.unit(&generator)
47 case "arctan2": Self.argument(&generator) + "," + Self.argument(&generator)
48 case "sinh", "cosh", "tanh": Self.argument(&generator, scale: 1)
49 case "sqrt": Self.argument(&generator).replacingOccurrences(of: "-", with: "")
50 default: Self.argument(&generator)
51 }
52 cases.append(("\(f)(\(x))", "(float 0)"))
53 }
54 var modes = Calc.Modes()
55 (modes.precision, modes.degrees, modes.format) = (precision, !radians, .float(0))
56 var refused: [String] = []
57 for (c, expected) in zip(cases, try CalcOracle.run(cases, precision: precision, radians: radians)) {
58 guard let ours = try? Calc.evaluate(c.0, modes: modes) else {
59 // Calc keeps a tangent of a quotient by zero unevaluated, and Calc's exp
60 // past 16 digits, worked out at two (four for tanh) digits more, isn't reproduced. Past
61 // 16 digits, two more don't always fit in a mantissa.
62 let name = String(c.0.prefix { $0 != "(" })
63 if precision <= 16, !expected.hasPrefix(name + "("), !(precision >= 13 && name == "tanh"), !(precision >= 15 && ["sinh", "cosh"].contains(name)) {
64 refused.append(c.0)
65 }
66 continue
67 }
68 #expect(ours == expected, "\(c.0) p\(precision) \(radians ? "rad" : "deg")")
69 }
70 #expect(refused == [], "p\(precision) \(radians ? "rad" : "deg") \(refused)")
71 }
72 }
73 }
74}
Tests/OrgCoreTests/CalcTests.swift +13 −4
@@ -4,7 +4,8 @@ import Testing
4 4
5/// Runs `calc-eval` with org's table modes over a list of expressions. 5/// Runs `calc-eval` with org's table modes over a list of expressions.
6enum CalcOracle { 6enum CalcOracle {
7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC", symbolic: Bool = false) throws -> [String] { 7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC", symbolic: Bool = false,
8 radians: Bool = false, fractions: Bool = false) throws -> [String] {
8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)") 9 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 10 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
10 defer { try? FileManager.default.removeItem(at: folder) } 11 defer { try? FileManager.default.removeItem(at: folder) }
@@ -27,6 +28,8 @@ enum CalcOracle {
27 (setq modes (plist-put modes 'calc-float-format format)) 28 (setq modes (plist-put modes 'calc-float-format format))
28 (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC")))) 29 (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC"))))
29 (when (getenv "ORACLE_SYMBOLIC") (setq modes (plist-put modes 'calc-symbolic-mode t))) 30 (when (getenv "ORACLE_SYMBOLIC") (setq modes (plist-put modes 'calc-symbolic-mode t)))
31 (when (getenv "ORACLE_RADIANS") (setq modes (plist-put modes 'calc-angle-mode 'rad)))
32 (when (getenv "ORACLE_FRACTIONS") (setq modes (plist-put modes 'calc-prefer-frac t)))
30 (let ((r (condition-case e (calc-eval (cons (car c) modes) nil) 33 (let ((r (condition-case e (calc-eval (cons (car c) modes) nil)
31 (error (format "LISP ERROR %S" e))))) 34 (error (format "LISP ERROR %S" e)))))
32 (if (stringp r) r (format "ERROR %S" r))))) 35 (if (stringp r) r (format "ERROR %S" r)))))
@@ -34,7 +37,10 @@ enum CalcOracle {
34 (with-temp-file (getenv "ORACLE_OUTPUT") 37 (with-temp-file (getenv "ORACLE_OUTPUT")
35 (insert (json-encode (vconcat results))))) 38 (insert (json-encode (vconcat results)))))
36 """#.write(to: script, atomically: true, encoding: .utf8) 39 """#.write(to: script, atomically: true, encoding: .utf8)
37 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone].merging(symbolic ? ["ORACLE_SYMBOLIC": "1"] : [:]) { $1 }) 40 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone]
41 .merging(symbolic ? ["ORACLE_SYMBOLIC": "1"] : [:]) { $1 }
42 .merging(radians ? ["ORACLE_RADIANS": "1"] : [:]) { $1 }
43 .merging(fractions ? ["ORACLE_FRACTIONS": "1"] : [:]) { $1 })
38 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output)) 44 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
39 } 45 }
40} 46}
@@ -224,14 +230,17 @@ struct CalcTests {
224 230
225 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the 231 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
226 /// cases `Calc.evaluate` doesn't support. 232 /// cases `Calc.evaluate` doesn't support.
227 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false) throws -> [String] { 233 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false,
228 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic) 234 radians: Bool = false, fractions: Bool = false) throws -> [String] {
235 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic, radians: radians, fractions: fractions)
229 #expect(emacs.count == cases.count) 236 #expect(emacs.count == cases.count)
230 var skipped: [String] = [] 237 var skipped: [String] = []
231 for (c, expected) in zip(cases, emacs) { 238 for (c, expected) in zip(cases, emacs) {
232 var modes = Calc.Modes() 239 var modes = Calc.Modes()
233 modes.precision = precision 240 modes.precision = precision
234 modes.symbolic = symbolic 241 modes.symbolic = symbolic
242 modes.degrees = !radians
243 modes.preferFractions = fractions
235 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)! 244 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
236 let f = c.1.dropFirst().dropLast().split(separator: " ") 245 let f = c.1.dropFirst().dropLast().split(separator: " ")
237 let n = Int(f[1])! 246 let n = Int(f[1])!