Calc: precision modes, fractions, percent, radix and more functions !410

merged merged by cmc on 2026-11-20 18:38 UTC · krz/orgstar:parity-calc into main

5 files changed, +968 −137

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +759 −99
@@ -46,22 +46,111 @@ public enum Calc {
46 /// `calc-eval` of `expression`, as the string Calc would return; with `numeric`, as 46 /// `calc-eval` of `expression`, as the string Calc would return; with `numeric`, as
47 /// `calc-eval` with `num`, a result that isn't a number is an error. 47 /// `calc-eval` with `num`, a result that isn't a number is an error.
48 public static func evaluate(_ expression: String, modes: Modes = Modes(), numeric: Bool = false) throws -> String { 48 public static func evaluate(_ expression: String, modes: Modes = Modes(), numeric: Bool = false) throws -> String {
49 guard modes.precision == 12 else { throw Unsupported("calc precision") } 49 // Mantissas live in an Int, so 18 digits at most.
50 var parser = Parser(expression) 50 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
51 let tree = try parser.parse() 51 return try $precision.withValue(modes.precision) {
52 let value = try Evaluator(modes: modes).eval(tree) 52 var parser = Parser(expression)
53 if numeric { 53 let tree = try parser.parse()
54 switch value { 54 let value = try Evaluator(modes: modes).eval(tree)
55 case .int, .float: break 55 if numeric {
56 default: throw Failure("Number expected") 56 switch value {
57 case .int, .float: break
58 default: throw Failure("Number expected")
59 }
57 } 60 }
61 return try format(value, modes.format)
58 } 62 }
59 return try format(value, modes.format)
60 } 63 }
61 64
62 // MARK: - Numbers 65 // MARK: - Numbers
63 66
64 static let precision = 12 67 /// `calc-internal-prec`.
68 @TaskLocal static var precision = 12
69
70 /// `math-with-extra-prec`: `body` with `n` more digits, the result rounded back.
71 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value {
72 let v = try $precision.withValue(precision + n, operation: body)
73 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) }
74 return v
75 }
76
77 /// `math-use-emacs-fn`: `f` on a double, as Calc does at up to 16 digits. Above that
78 /// Calc uses its own series, which isn't reproduced.
79 static func emacs(_ f: (Double) -> Double, _ x: Value) throws -> Value {
80 guard precision <= 16 else { throw Unsupported("calc precision") }
81 guard case .float(let m, let e) = x, (-300...300).contains(e + digits(Int128(m)) - 1),
82 let d = Double("\(m)e\(e)") else { throw Unsupported("number size") }
83 let r = f(d)
84 guard r.isFinite else { throw Unsupported("infinite result") }
85 // `number-to-string`: the shortest text that reads back as the same double.
86 let pieces = r.description.split(separator: "e")
87 let text = String(pieces[0])
88 let point = text.firstIndex(of: ".").map { text.distance(from: $0, to: text.endIndex) - 1 } ?? 0
89 guard let mantissa = Int128(text.replacingOccurrences(of: ".", with: "")),
90 let exponent = Int(pieces.count > 1 ? String(pieces[1]) : "0") else { throw Unsupported("number") }
91 return try makeFloat(mantissa, exponent - point)
92 }
93
94 // Constants to 36 digits, rounded to the precision, as `math-defcache` gives them.
95 static func pi() throws -> Value { try makeFloat(314159265358979323846264338327950288, -35) }
96 static func piOver2() throws -> Value { try makeFloat(157079632679489661923132169163975144, -35) }
97 static func piOver180() throws -> Value { try makeFloat(174532925199432957692369076848861271, -37) }
98
99 /// `math-float`.
100 static func float(_ v: Value) throws -> Value {
101 switch v {
102 case .int(let i): return try makeFloat(Int128(i), 0)
103 case .frac(let n, let d): return try divide(try makeFloat(Int128(n), 0), .int(d))
104 case .float: return v
105 default: throw Unsupported("arguments")
106 }
107 }
108
109 static func isZero(_ v: Value) -> Bool { v == .int(0) || v == .float(0, 0) }
110
111 /// The sign of a real number.
112 static func sign(_ v: Value) throws -> Int {
113 switch v {
114 case .int(let i): return i.signum()
115 case .float(let m, _): return m.signum()
116 case .frac(let n, _): return n.signum()
117 default: throw Unsupported("arguments")
118 }
119 }
120
121 /// `math-trunc` of a real number, as an integer.
122 static func trunc(_ v: Value) throws -> Int {
123 switch v {
124 case .int(let i): return i
125 case .frac(let n, let d): return n / d
126 case .float(let m, let e):
127 let t = e >= 0 ? try scaleRounding(Int128(m), e) : -e > 37 ? 0 : Int128(m) / (try power10(-e))
128 guard let i = Int(exactly: t) else { throw Unsupported("integer size") }
129 return i
130 default: throw Unsupported("arguments")
131 }
132 }
133
134 /// `Math-num-integerp`: an integer, or a float with an integer value.
135 static func isWhole(_ v: Value) -> Bool {
136 switch v {
137 case .int: true
138 case .float(_, let e): e >= 0
139 default: false
140 }
141 }
142
143 /// `math-nearly-equal-float`: equal but for the last digit of precision.
144 static func nearlyEqual(_ a: Value, _ b: Value) -> Bool {
145 guard case .float(let ma, let ea) = a, case .float(let mb, let eb) = b else { return false }
146 let (x, y) = (Int128(ma), Int128(mb))
147 switch ea - eb {
148 case 0: return x == y || (abs(y - x) < 10 && digits(x) == precision)
149 case 1: return abs(x * 10 - y) < 10 && digits(y) == precision
150 case -1: return abs(y * 10 - x) < 10 && digits(x) == precision
151 default: return false
152 }
153 }
65 154
66 static func digits(_ x: Int128) -> Int { 155 static func digits(_ x: Int128) -> Int {
67 var n = x.magnitude 156 var n = x.magnitude
@@ -108,12 +197,14 @@ public enum Calc {
108 m /= 10 197 m /= 10
109 e += 1 198 e += 1
110 } 199 }
111 return .float(Int(m), e) 200 guard let i = Int(exactly: m) else { throw Unsupported("calc precision") }
201 return .float(i, e)
112 } 202 }
113 203
114 static func parts(_ v: Value) throws -> (Int128, Int) { 204 static func parts(_ v: Value) throws -> (Int128, Int) {
115 switch v { 205 switch v {
116 case .int(let i): return (Int128(i), 0) 206 // `math-float`: normalized and rounded, as Calc converts an integer to combine it with a float.
207 case .int(let i): return try parts(try makeFloat(Int128(i), 0))
117 case .float(let m, let e): return (Int128(m), e) 208 case .float(let m, let e): return (Int128(m), e)
118 case .frac(let n, let d): return try parts(try divide(.int(n), .int(d))) 209 case .frac(let n, let d): return try parts(try divide(.int(n), .int(d)))
119 case .vector: throw Unsupported("vector arithmetic") 210 case .vector: throw Unsupported("vector arithmetic")
@@ -163,6 +254,8 @@ public enum Calc {
163 } 254 }
164 255
165 static func fromDouble(_ d: Double) throws -> Value { 256 static func fromDouble(_ d: Double) throws -> Value {
257 // Calc works these out at two digits more; past 16 it uses its own series.
258 guard precision <= 14 else { throw Unsupported("calc precision") }
166 guard d.isFinite else { throw Unsupported("infinite result") } 259 guard d.isFinite else { throw Unsupported("infinite result") }
167 if d == 0 { return .float(0, 0) } 260 if d == 0 { return .float(0, 0) }
168 // Seventeen significant digits are exact for a Double; rounding to 12 follows. 261 // Seventeen significant digits are exact for a Double; rounding to 12 follows.
@@ -290,12 +383,56 @@ public enum Calc {
290 return try multiply(a, try integerPower(square, n / 2)) 383 return try multiply(a, try integerPower(square, n / 2))
291 } 384 }
292 385
386 /// `math-pow` of real numbers.
293 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value { 387 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
294 if isNaN(a, b) { return .nan } 388 if isNaN(a, b) { return .nan }
295 if case .int(let n) = b { return try integerPower(a, n, fractions: fractions) } 389 _ = (try sign(a), try sign(b))
296 let base = try double(a) 390 var floatB = false
297 guard base >= 0 else { throw Unsupported("complex result") } 391 if case .float = b { floatB = true }
298 return try fromDouble(pow(base, try double(b))) 392 if isZero(a) {
393 // `math-pow-of-zero`.
394 if b == .int(0) { return .int(1) }
395 if isZero(b) { throw Unsupported("arguments") }
396 guard try sign(b) > 0 else { throw Unsupported("division by zero") }
397 return floatB ? try float(a) : a
398 }
399 if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a }
400 if isZero(b) {
401 if case .float = a { return .float(1, 0) }
402 return floatB ? .float(1, 0) : .int(1)
403 }
404 if case .int(let n) = b {
405 if a == .float(1, 1) { return try makeFloat(1, n) }
406 return try extra(2) { try integerPower(a, n, fractions: fractions) }
407 }
408 // `math-pow-fancy`.
409 if let q = quarter(b), (1...3).contains(q) {
410 let root = try squareRoot(floatB ? try float(a) : a)
411 return try power(root, try multiply(.int(2), b), fractions: fractions)
412 }
413 if case .frac(let num, let den) = b, den <= 10, try sign(a) > 0 {
414 return try integerPower(try nthRoot(a, den), num, fractions: fractions)
415 }
416 if a == .int(10) || a == .float(1, 1), isWhole(b) { return try makeFloat(1, try trunc(b)) }
417 guard try sign(a) > 0 else { throw Unsupported("complex result") }
418 return try extra(2) { try expRaw(try float(try multiply(b, try lnRaw(try float(a))))) }
419 }
420
421 /// `math-quarter-integer`: 0 for an integer, 1 to 3 for a number of quarters, else nil.
422 static func quarter(_ x: Value) -> Int? {
423 switch x {
424 case .int: return 0
425 case .frac(let n, let d):
426 if n < 0 { return quarter(.frac(-n, d)).map { 4 - $0 } }
427 return d == 2 ? 2 : d == 4 ? n % 4 : nil
428 case .float(let m, let e):
429 if m < 0 { return quarter(.float(-m, e)).map { 4 - $0 } }
430 if e >= 0 { return 0 }
431 if e == -1 { return m % 10 == 5 ? 2 : nil }
432 if e == -2 { return m % 100 == 25 ? 1 : m % 100 == 75 ? 3 : nil }
433 return nil
434 default: return nil
435 }
299 } 436 }
300 437
301 static func compare(_ a: Value, _ b: Value) throws -> Int { 438 static func compare(_ a: Value, _ b: Value) throws -> Int {
@@ -306,6 +443,262 @@ public enum Calc {
306 return m == 0 ? 0 : (m < 0 ? -1 : 1) 443 return m == 0 ? 0 : (m < 0 ? -1 : 1)
307 } 444 }
308 445
446 static func absolute(_ v: Value) throws -> Value { try sign(v) < 0 ? try negate(v) : v }
447
448 /// `math-floor` of a real number, as an integer.
449 static func floorInt(_ v: Value) throws -> Int {
450 let t = try trunc(v)
451 return try sign(v) < 0 && compare(v, .int(t)) != 0 ? t - 1 : t
452 }
453
454 // MARK: - Roots, logarithms and rounding
455
456 /// `math-sqrt` of a real number.
457 static func squareRoot(_ a: Value) throws -> Value {
458 if isZero(a) { return a }
459 guard try sign(a) > 0 else { throw Unsupported("complex result") }
460 func exact(_ i: Int) -> Int? {
461 let guess = Int(Double(i).squareRoot())
462 return [guess - 1, guess, guess + 1].first { $0 >= 0 && $0.multipliedReportingOverflow(by: $0) == (i, false) }
463 }
464 if case .int(let i) = a, let root = exact(i) { return .int(root) }
465 if case .frac(let n, let d) = a, let rn = exact(n), let rd = exact(d) { return .frac(rn, rd) }
466 let x = try float(a)
467 return try extra(1) { try squareRootRaw(x) }
468 }
469
470 /// `math-sqrt-raw` of a float.
471 static func squareRootRaw(_ a: Value) throws -> Value {
472 if isZero(a) { return a }
473 guard try sign(a) > 0 else { throw Unsupported("complex result") }
474 return try emacs({ $0.squareRoot() }, a)
475 }
476
477 /// `math-exp-raw` of a float.
478 static func expRaw(_ x: Value) throws -> Value {
479 isZero(x) ? .float(1, 0) : try emacs({ Foundation.exp($0) }, x)
480 }
481
482 /// `math-ln-raw` of a float.
483 static func lnRaw(_ x: Value) throws -> Value {
484 if x == .float(1, 0) { return .float(0, 0) }
485 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
486 return try emacs({ Foundation.log($0) }, x)
487 }
488
489 /// `math-arctan-raw` of a float.
490 static func arctanRaw(_ x: Value) throws -> Value {
491 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) }
492 return isZero(x) ? x : try emacs({ Foundation.atan($0) }, x)
493 }
494
495 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) }
496 static func ln10() throws -> Value { try makeFloat(230258509299404568401799145468436421, -35) }
497
498 /// `math-ln-raw-2`: the logarithm of a positive float by Calc's series.
499 static func lnRaw2(_ x: Value) throws -> Value {
500 if try compare(.float(14, -1), x) < 0 { return try add(try lnRaw2(try multiply(x, .float(5, -1))), try ln2()) }
501 let y = try divide(try subtract(x, .float(1, 0)), try add(x, .float(1, 0)))
502 let square = try multiply(y, y)
503 var (sum, power, n) = (y, y, 3)
504 for _ in 0..<10000 {
505 power = try multiply(power, square)
506 let next = try add(sum, try divide(power, try float(.int(n))))
507 if nearlyEqual(sum, next) { return try multiply(sum, .float(2, 0)) }
508 (sum, n) = (next, n + 2)
509 }
510 throw Unsupported("number")
511 }
512
513 /// `math-nth-root-integer`: the integer root rounded down, and whether it is exact.
514 static func integerRoot(_ a: Int, _ n: Int) throws -> (Bool, Int) {
515 let a = Int128(a)
516 var guess = try power10((digits(a) + n - 1) / n)
517 while true {
518 var p: Int128 = 1
519 for _ in 0..<(n - 1) {
520 let (r, overflow) = p.multipliedReportingOverflow(by: guess)
521 if overflow { throw Unsupported("integer size") }
522 p = r
523 }
524 let (q, r) = a.quotientAndRemainder(dividingBy: p)
525 let (g2, r2) = (q + Int128(n - 1) * guess).quotientAndRemainder(dividingBy: Int128(n))
526 if g2 < guess {
527 guess = g2
528 continue
529 }
530 return (g2 == guess && r == 0 && r2 == 0, Int(guess))
531 }
532 }
533
534 /// `math-nth-root-float`: Newton's method at one digit more.
535 static func floatRoot(_ a: Value, _ n: Int, guess: Value? = nil) throws -> Value {
536 try extra(1) {
537 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
538 let nf = try makeFloat(Int128(n), 0)
539 let nfm1 = try makeFloat(Int128(n - 1), 0)
540 var g = try guess ?? makeFloat(1, (digits(Int128(m)) + e + n / 2) / n)
541 for _ in 0..<1000 {
542 let g2 = try divide(try add(try multiply(nfm1, g), try divide(a, try integerPower(g, n - 1))), nf)
543 if nearlyEqual(g2, g) { return g2 }
544 g = g2
545 }
546 throw Unsupported("number")
547 }
548 }
549
550 /// `math-nth-root` of a positive real number.
551 static func nthRoot(_ a: Value, _ n: Int) throws -> Value {
552 switch a {
553 case .int(let i):
554 let (exact, root) = try integerRoot(i, n)
555 return exact ? .int(root) : try floatRoot(try float(a), n, guess: try float(.int(root)))
556 case .frac(let num, let den):
557 let (e1, r1) = try integerRoot(num, n)
558 let (e2, r2) = try integerRoot(den, n)
559 if e1 && e2 { return .frac(r1, r2) }
560 return try floatRoot(try float(a), n, guess: try divide(try float(.int(r1)), try float(.int(r2))))
561 default:
562 return try floatRoot(a, n)
563 }
564 }
565
566 /// `math-pow` of a real number to the power `1:n`.
567 static func rootPower(_ a: Value, _ n: Int) throws -> Value {
568 if isZero(a) || a == .int(1) || a == .float(1, 0) { return a }
569 guard try sign(a) > 0 else { throw Unsupported("complex result") }
570 switch n {
571 case 1: return a
572 case 2: return try squareRoot(a)
573 case 4: return try squareRoot(try squareRoot(a))
574 case 3...10: return try nthRoot(a, n)
575 default: return try extra(2) { try expRaw(try float(try multiply(.frac(1, n), try lnRaw(try float(a))))) }
576 }
577 }
578
579 /// `math-integer-log`: the largest n with b^n at most x, and whether b^n is x.
580 static func integerLog(_ x: Value, _ b: Value) throws -> (Bool, Int) {
581 var pows = [b]
582 var pow = try multiply(b, b)
583 while try compare(x, pow) >= 0 {
584 pows.insert(pow, at: 0)
585 pow = try multiply(pow, pow)
586 }
587 var n = 1 << (pows.count - 1)
588 var sum = n
589 pow = pows[0]
590 var rest = pows.dropFirst()
591 while let next = rest.first, try compare(pow, x) < 0 {
592 rest = rest.dropFirst()
593 n /= 2
594 let candidate = try multiply(pow, next)
595 if try compare(x, candidate) >= 0 {
596 pow = candidate
597 sum += n
598 }
599 }
600 return (pow == x, sum)
601 }
602
603 /// `math-round` in `math-rounding-mode` `even` or `up`.
604 static func round(_ a: Value, even: Bool) throws -> Value {
605 if isWhole(a) { return .int(try trunc(a)) }
606 if try sign(a) < 0, even { return try negate(try round(try negate(a), even: even)) }
607 let b = try add(a, rational(a) != nil ? .frac(1, 2) : .float(5, -1))
608 var f = try floorInt(b)
609 if even, isWhole(b), f % 2 != 0 { f -= 1 }
610 return .int(f)
611 }
612
613 /// `calcFunc-scf`: `x` times 10^n.
614 static func scale(_ x: Value, _ n: Int, fractions: Bool) throws -> Value {
615 if n == 0 { return x }
616 guard abs(n) <= 18 else { throw Unsupported("number size") }
617 let p = Int(try power10(abs(n)))
618 switch x {
619 case .int: return n > 0 ? try multiply(x, .int(p)) : try divide(x, .int(p), fractions: fractions)
620 case .frac(let a, let b):
621 let (num, o1) = a.multipliedReportingOverflow(by: n > 0 ? p : 1)
622 let (den, o2) = b.multipliedReportingOverflow(by: n > 0 ? 1 : p)
623 if o1 || o2 { throw Unsupported("integer size") }
624 return try fraction(num, den)
625 case .float(let m, let e): return try makeFloat(Int128(m), e + n)
626 default: throw Unsupported("arguments")
627 }
628 }
629
630 /// `calcFunc-frac`: the fraction closest to a float within its precision.
631 static func toFraction(_ a: Value) throws -> Value {
632 if rational(a) != nil { return a }
633 if isWhole(a) { return .int(try trunc(a)) }
634 if try sign(a) < 0 { return try negate(try toFraction(try negate(a))) }
635 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
636 let tolerance = Value.float(5, digits(Int128(m)) + e - (1 + precision))
637 /// `math-eval-continued-fraction`.
638 func evaluate(_ terms: [Int], fractions: Bool) throws -> Value {
639 var n = Value.int(terms.last!)
640 var d = Value.int(1)
641 for c in terms.reversed().dropFirst() { (n, d) = (try add(try multiply(.int(c), n), d), n) }
642 return try divide(n, d, fractions: fractions)
643 }
644 let terms = try $precision.withValue(precision + 2) {
645 var terms: [Int] = []
646 var aa = a
647 while try terms.isEmpty || (!isZero(aa) && compare(try absolute(try subtract(a, try evaluate(terms, fractions: false))), tolerance) >= 0) {
648 guard terms.count < 100 else { throw Unsupported("number") }
649 let whole = try trunc(aa)
650 aa = try subtract(aa, .int(whole))
651 terms.append(whole)
652 if !isZero(aa) { aa = try divide(.int(1), aa) }
653 }
654 return terms
655 }
656 return try evaluate(terms, fractions: true)
657 }
658
659 /// `calcFunc-gcd`.
660 static func gcd(_ a: Value, _ b: Value) throws -> Value {
661 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
662 let a = isWhole(a) ? .int(try trunc(a)) : a
663 let b = isWhole(b) ? .int(try trunc(b)) : b
664 if case .int(let x) = a, case .int(let y) = b {
665 guard x != .min, y != .min else { throw Unsupported("integer size") }
666 return .int(gcd(x, y))
667 }
668 if try sign(a) < 0 { return try Calc.gcd(try negate(a), b) }
669 if try sign(b) < 0 { return try Calc.gcd(a, try negate(b)) }
670 guard let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { throw Unsupported("arguments") }
671 guard case .int(let g) = try Calc.gcd(.int(d1), .int(d2)) else { throw Unsupported("arguments") }
672 let (product, overflow) = d1.multipliedReportingOverflow(by: d2 / g)
673 if overflow { throw Unsupported("integer size") }
674 return try fraction(gcd(n1, n2), product)
675 }
676
677 /// `calcFunc-choose` of integers.
678 static func choose(_ n: Int, _ m: Int) throws -> Int {
679 if m >= 0, m <= n {
680 var c = 1
681 var top = n
682 for i in stride(from: 1, through: m > n / 2 ? n - m : m, by: 1) {
683 let (product, overflow) = c.multipliedReportingOverflow(by: top)
684 if overflow { throw Unsupported("integer size") }
685 c = product / i
686 top -= 1
687 }
688 return c
689 }
690 if n < 0, m >= 0 {
691 let v = try choose(m - n - 1, m)
692 return m % 2 == 0 ? v : -v
693 }
694 if n < 0 {
695 if n < m { return 0 }
696 let v = try choose(-m - 1, n - m)
697 return (n - m) % 2 == 0 ? v : -v
698 }
699 return 0
700 }
701
309 // MARK: - Display 702 // MARK: - Display
310 703
311 /// `math-format-number`. 704 /// `math-format-number`.
@@ -488,15 +881,32 @@ public enum Calc {
488 return left 881 return left
489 } 882 }
490 883
884 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`.
491 mutating func product() throws -> Node { 885 mutating func product() throws -> Node {
492 var left = try unary() 886 var left = try unary()
493 while peek() == "*" { 887 while let c = peek() {
494 i += 1 888 if c == "*" {
889 i += 1
890 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
891 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
892 break
893 }
495 left = .binary("*", left, try unary()) 894 left = .binary("*", left, try unary())
496 } 895 }
497 return left 896 return left
498 } 897 }
499 898
899 /// `math-factor-after`: whether what follows can start an operand, which makes `%`
900 /// the modulo operator rather than percent.
901 func factorAfter(_ j: Int) -> Bool {
902 var j = j
903 while j < chars.count, chars[j] == " " || chars[j] == "\t" { j += 1 }
904 guard j < chars.count else { return false }
905 let c = chars[j]
906 if c == ".", j + 1 < chars.count { return chars[j + 1].isASCII && chars[j + 1].isNumber }
907 return (c.isASCII && c.isNumber) || c.isLetter || "$#\"-+!([{".contains(c)
908 }
909
500 mutating func unary() throws -> Node { 910 mutating func unary() throws -> Node {
501 if let c = peek(), c == "-" || c == "+" { 911 if let c = peek(), c == "-" || c == "+" {
502 i += 1 912 i += 1
@@ -507,7 +917,28 @@ public enum Calc {
507 } 917 }
508 918
509 mutating func powerNode() throws -> Node { 919 mutating func powerNode() throws -> Node {
510 let base = try primary() 920 var base = try primary()
921 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
922 while let c = peek() {
923 let next = i + 1 < chars.count ? chars[i + 1] : nil
924 if c == "%", !factorAfter(i + 1) {
925 // `%%` starts a comment.
926 if next == "%" { throw Unsupported("formula syntax") }
927 i += 1
928 base = .call("percent", [base])
929 } else if c == "!", next != "=" {
930 if next == "!" {
931 if i + 2 < chars.count, chars[i + 2] == "!" { throw Unsupported("formula syntax") }
932 i += 2
933 base = .call("dfact", [base])
934 } else {
935 i += 1
936 base = .call("fact", [base])
937 }
938 } else {
939 break
940 }
941 }
511 if peek() == "^" { 942 if peek() == "^" {
512 i += 1 943 i += 1
513 return .binary("^", base, try unary()) 944 return .binary("^", base, try unary())
@@ -571,15 +1002,44 @@ public enum Calc {
571 throw Unsupported("formula syntax") 1002 throw Unsupported("formula syntax")
572 } 1003 }
573 1004
574 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`. 1005 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
1006 /// and `1:2:3`, and integers in a radix, `16#FF`.
575 mutating func number() throws -> Value { 1007 mutating func number() throws -> Value {
576 var whole = "" 1008 var whole = ""
577 while i < chars.count, chars[i].isASCII, chars[i].isNumber { 1009 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
578 whole.append(chars[i]) 1010 whole.append(chars[i])
579 i += 1 1011 i += 1
580 } 1012 }
1013 if !whole.isEmpty, i + 1 < chars.count, chars[i] == ":", chars[i + 1].isASCII, chars[i + 1].isNumber {
1014 var text = whole
1015 while i < chars.count, chars[i] == ":" || (chars[i].isASCII && chars[i].isNumber) {
1016 text.append(chars[i])
1017 i += 1
1018 }
1019 let parts = text.split(separator: ":", omittingEmptySubsequences: false).map { Int($0) }
1020 guard parts.count <= 3, !parts.contains(nil) else { throw Unsupported("formula syntax") }
1021 let n = parts.map { $0! }
1022 guard n.last != 0 else { throw Unsupported("formula syntax") }
1023 if n.count == 2 { return try fraction(n[0], n[1]) }
1024 let (product, o1) = n[0].multipliedReportingOverflow(by: n[2])
1025 let (sum, o2) = product.addingReportingOverflow(n[1])
1026 if o1 || o2 { throw Unsupported("integer size") }
1027 return try fraction(sum, n[2])
1028 }
1029 if !whole.isEmpty, i < chars.count, chars[i] == "#" {
1030 i += 1
1031 var text = ""
1032 while i < chars.count, chars[i].isASCII, chars[i].isLetter || chars[i].isNumber || chars[i] == "." || chars[i] == ":" || chars[i] == "#" {
1033 text.append(chars[i])
1034 i += 1
1035 }
1036 guard let radix = Int(whole), (2...36).contains(radix), !text.isEmpty,
1037 let value = Int(text, radix: radix) else { throw Unsupported("formula syntax") }
1038 return .int(value)
1039 }
581 var fraction: String? 1040 var fraction: String?
582 if i < chars.count, chars[i] == "." { 1041 // `2..5` is an interval, not `2.` then `.5`.
1042 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
583 i += 1 1043 i += 1
584 var f = "" 1044 var f = ""
585 while i < chars.count, chars[i].isASCII, chars[i].isNumber { 1045 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
@@ -630,40 +1090,44 @@ public enum Calc {
630 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1) 1090 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1)
631 case .unary(_, let operand): return try negate(try eval(operand)) 1091 case .unary(_, let operand): return try negate(try eval(operand))
632 case .binary(let op, let l, let r): 1092 case .binary(let op, let l, let r):
633 let a = try eval(l) 1093 return try binary(op, try eval(l), try eval(r))
634 let b = try eval(r)
635 switch op {
636 case "+": return try add(a, b)
637 case "-": return try subtract(a, b)
638 case "*": return try multiply(a, b)
639 case "/": return try divide(a, b, fractions: modes.preferFractions)
640 case "%": return try mod(a, b)
641 case "\\": return try idiv(a, b)
642 case "^": return try power(a, b, fractions: modes.preferFractions)
643 case "|": return .int(try truth(a) || truth(b) ? 1 : 0)
644 case "&": return .int(try truth(a) && truth(b) ? 1 : 0)
645 default:
646 let order = try compare(a, b)
647 let holds = switch op {
648 case "=": order == 0
649 case "≠": order != 0
650 case "<": order < 0
651 case ">": order > 0
652 case "≤": order <= 0
653 default: order >= 0
654 }
655 return .int(holds ? 1 : 0)
656 }
657 case .call(let name, let args): 1094 case .call(let name, let args):
658 return try call(name, try args.map(eval)) 1095 return try call(name, try args.map(eval))
659 } 1096 }
660 } 1097 }
661 1098
1099 func binary(_ op: Character, _ a: Value, _ b: Value) throws -> Value {
1100 switch op {
1101 case "+": return try add(a, b)
1102 case "-": return try subtract(a, b)
1103 case "*": return try multiply(a, b)
1104 case "/": return try divide(a, b, fractions: modes.preferFractions)
1105 case "%": return try mod(a, b)
1106 case "\\": return try idiv(a, b)
1107 case "^": return try power(a, b, fractions: modes.preferFractions)
1108 // `calcFunc-lor` and `calcFunc-land` give one of their arguments.
1109 case "|": return try truth(a) ? a : b
1110 case "&": return try truth(a) ? b : a
1111 default:
1112 let order = try compare(a, b)
1113 let holds = switch op {
1114 case "=": order == 0
1115 case "≠": order != 0
1116 case "<": order < 0
1117 case ">": order > 0
1118 case "≤": order <= 0
1119 default: order >= 0
1120 }
1121 return .int(holds ? 1 : 0)
1122 }
1123 }
1124
662 /// A condition's value: a number, nonzero for true. 1125 /// A condition's value: a number, nonzero for true.
663 func truth(_ v: Value) throws -> Bool { 1126 func truth(_ v: Value) throws -> Bool {
664 switch v { 1127 switch v {
665 case .int(let i): return i != 0 1128 case .int(let i): return i != 0
666 case .float(let m, _): return m != 0 1129 case .float(let m, _): return m != 0
1130 case .frac: return true
667 default: throw Unsupported("condition") 1131 default: throw Unsupported("condition")
668 } 1132 }
669 } 1133 }
@@ -695,26 +1159,36 @@ public enum Calc {
695 return .int(i) 1159 return .int(i)
696 } 1160 }
697 1161
698 /// The sum of squared deviations from the mean, and the count. 1162 /// `math-covariance` of numbers without error forms: the variance of `xs` without `ys`,
699 func deviations(_ args: [Value]) throws -> (Value, Int) { 1163 /// with `correlation` the correlation coefficient.
700 let items = try elements(args) 1164 func covariance(_ xs: [Value], _ ys: [Value]? = nil, population: Bool, correlation: Bool = false) throws -> Value {
701 guard !items.isEmpty else { throw Unsupported("empty vector") } 1165 let n = xs.count
702 let mean = try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) 1166 guard n > 0 else { throw Unsupported("empty vector") }
703 let squares = try items.reduce(Value.int(0)) { sum, x in 1167 guard population || n > 1 else { throw Unsupported(ys == nil ? "variance of one value" : "arguments") }
704 let d = try subtract(x, mean) 1168 guard (ys ?? xs).count == n else { throw Unsupported("arguments") }
705 return try add(sum, try multiply(d, d)) 1169 return try extra(2) {
1170 func sum(_ v: [Value]) throws -> Value { try v.dropFirst().reduce(v[0], add) }
1171 func deviations(_ v: [Value]) throws -> [Value] {
1172 let shift = try divide(try sum(v), .int(-n), fractions: modes.preferFractions)
1173 return try v.map { try add($0, shift) }
1174 }
1175 let dx = try deviations(xs)
1176 let dy = try ys.map(deviations) ?? dx
1177 let products = try sum(try zip(dx, dy).map(multiply))
1178 let divisor = correlation
1179 ? try squareRoot(try multiply(try sum(try dx.map { try multiply($0, $0) }), try sum(try dy.map { try multiply($0, $0) })))
1180 : .int(population ? n : n - 1)
1181 return try divide(products, divisor, fractions: modes.preferFractions)
706 } 1182 }
707 return (squares, items.count)
708 }
709
710 func root(_ x: Value) throws -> Value {
711 try call("sqrt", [x])
712 } 1183 }
713 1184
1185 /// `math-flatten-many-vecs`: the arguments, vectors flattened into their elements.
714 func elements(_ args: [Value]) throws -> [Value] { 1186 func elements(_ args: [Value]) throws -> [Value] {
715 guard args.count == 1 else { throw Unsupported("arguments") } 1187 var items: [Value] = []
716 if case .vector(let items) = args[0] { return items } 1188 for arg in args {
717 return [args[0]] 1189 if case .vector(let inner) = arg { items += try elements(inner) } else { items.append(arg) }
1190 }
1191 return items
718 } 1192 }
719 1193
720 func one(_ args: [Value]) throws -> Value { 1194 func one(_ args: [Value]) throws -> Value {
@@ -729,23 +1203,27 @@ public enum Calc {
729 func call(_ name: String, _ args: [Value]) throws -> Value { 1203 func call(_ name: String, _ args: [Value]) throws -> Value {
730 switch name { 1204 switch name {
731 case "vsum": 1205 case "vsum":
732 return try elements(args).reduce(Value.int(0)) { try add($0, $1) } 1206 return try extra(2) { try elements(args).reduce(Value.int(0)) { try add($0, $1) } }
733 case "vprod": 1207 case "vprod":
734 return try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } 1208 return try extra(2) { try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } }
735 case "vcount": 1209 case "vcount":
736 return .int(try elements(args).count) 1210 return .int(try elements(args).count)
737 case "vmean": 1211 case "vmean":
738 let items = try elements(args) 1212 let items = try elements(args)
739 guard !items.isEmpty else { throw Unsupported("empty vector") } 1213 guard !items.isEmpty else { throw Unsupported("empty vector") }
740 return try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) 1214 return try extra(2) { try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) }
741 case "vmax", "vmin": 1215 case "vmax", "vmin":
1216 // `math-reduce-many-vecs` compares at two digits more.
742 let items = try elements(args) 1217 let items = try elements(args)
743 guard var best = items.first else { throw Unsupported("empty vector") } 1218 guard let first = items.first else { throw Unsupported("empty vector") }
744 for item in items.dropFirst() { 1219 return try extra(2) {
745 let order = try compare(item, best) 1220 var best = first
746 if name == "vmax" ? order > 0 : order < 0 { best = item } 1221 for item in items.dropFirst() {
1222 let order = try compare(item, best)
1223 if name == "vmax" ? order > 0 : order < 0 { best = item }
1224 }
1225 return best
747 } 1226 }
748 return best
749 case "vmedian": 1227 case "vmedian":
750 var items = try elements(args) 1228 var items = try elements(args)
751 guard !items.isEmpty else { throw Unsupported("empty vector") } 1229 guard !items.isEmpty else { throw Unsupported("empty vector") }
@@ -756,22 +1234,21 @@ public enum Calc {
756 guard args.count == 3 else { throw Unsupported("arguments") } 1234 guard args.count == 3 else { throw Unsupported("arguments") }
757 return try truth(args[0]) ? args[1] : args[2] 1235 return try truth(args[0]) ? args[1] : args[2]
758 case "vvar", "vpvar", "vsdev", "vpsdev": 1236 case "vvar", "vpvar", "vsdev", "vpsdev":
759 let (squares, n) = try deviations(args) 1237 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
760 let population = name == "vpvar" || name == "vpsdev" 1238 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance
761 if !population, n < 2 { throw Unsupported("variance of one value") }
762 let variance = try divide(squares, .int(population ? n : n - 1), fractions: modes.preferFractions)
763 return name.hasSuffix("sdev") ? try root(variance) : variance
764 case "mod": 1239 case "mod":
765 guard args.count == 2 else { throw Unsupported("arguments") } 1240 guard args.count == 2 else { throw Unsupported("arguments") }
766 return try mod(args[0], args[1]) 1241 return try mod(args[0], args[1])
767 case "idiv": 1242 case "idiv":
768 guard args.count == 2 else { throw Unsupported("arguments") } 1243 guard args.count == 2 else { throw Unsupported("arguments") }
769 return try idiv(args[0], args[1]) 1244 return try idiv(args[0], args[1])
770 case "fact": 1245 case "fact", "dfact":
771 guard case .int(let n) = try one(args), n >= 0 else { throw Unsupported("arguments") } 1246 // A float with an integer value gives a float, up to 20.
1247 let x = try one(args)
1248 guard isWhole(x), case let n = try trunc(x), n >= 0, x == .int(n) || (name == "fact" && n <= 20) else { throw Unsupported("arguments") }
772 var result = Value.int(1) 1249 var result = Value.int(1)
773 for k in stride(from: 2, through: n, by: 1) { result = try multiply(result, .int(k)) } 1250 for k in stride(from: name == "fact" ? 2 : 2 + n % 2, through: n, by: name == "fact" ? 1 : 2) { result = try multiply(result, .int(k)) }
774 return result 1251 return x == .int(n) ? result : try float(result)
775 case "max", "min": 1252 case "max", "min":
776 guard !args.isEmpty else { throw Unsupported("arguments") } 1253 guard !args.isEmpty else { throw Unsupported("arguments") }
777 var best = args[0] 1254 var best = args[0]
@@ -804,30 +1281,16 @@ public enum Calc {
804 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") } 1281 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") }
805 return .int(i) 1282 return .int(i)
806 case "sqrt": 1283 case "sqrt":
807 let x = try one(args) 1284 return try squareRoot(try one(args))
808 func exactRoot(_ i: Int) -> Int? {
809 guard i >= 0 else { return nil }
810 let root = Int(Double(i).squareRoot().rounded())
811 return root.multipliedReportingOverflow(by: root) == (i, false) ? root : nil
812 }
813 if case .int(let i) = x {
814 guard i >= 0 else { throw Unsupported("complex result") }
815 if let root = exactRoot(i) { return .int(root) }
816 }
817 if case .frac(let n, let d) = x, let rn = exactRoot(n), let rd = exactRoot(d) { return try fraction(rn, rd) }
818 let d = try double(x)
819 guard d >= 0 else { throw Unsupported("complex result") }
820 return try fromDouble(d.squareRoot())
821 case "exp": 1285 case "exp":
822 let x = try one(args) 1286 let x = try one(args)
823 if x == .int(0) { return .int(1) } 1287 if x == .int(0) { return .int(1) }
824 return try fromDouble(Foundation.exp(try double(x))) 1288 return try extra(2) { try expRaw(try float(x)) }
825 case "ln": 1289 case "ln":
826 let x = try one(args) 1290 let x = try one(args)
827 if x == .int(1) { return .int(0) } 1291 if x == .int(1) { return .int(0) }
828 let d = try double(x) 1292 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
829 guard d > 0 else { throw Unsupported("logarithm domain") } 1293 return try extra(2) { try lnRaw(try float(x)) }
830 return try fromDouble(Foundation.log(d))
831 case "log10": 1294 case "log10":
832 let x = try one(args) 1295 let x = try one(args)
833 if case .int(let i) = x, i > 0 { 1296 if case .int(let i) = x, i > 0 {
@@ -839,9 +1302,14 @@ public enum Calc {
839 } 1302 }
840 if n == 1 { return .int(k) } 1303 if n == 1 { return .int(k) }
841 } 1304 }
842 let d = try double(x) 1305 if case .frac(1, let d) = x, case (true, let k) = try integerLog(.int(d), .int(10)) { return .int(-k) }
843 guard d > 0 else { throw Unsupported("logarithm domain") } 1306 if isZero(x) { throw Unsupported("logarithm domain") }
844 return try fromDouble(Foundation.log10(d)) 1307 return try extra(2) {
1308 guard case .float(let m, let e) = try float(x), m > 0 else { throw Unsupported("logarithm domain") }
1309 if m == 1 { return try float(.int(e)) }
1310 let digits = digits(Int128(m)) - 1
1311 return try add(try divide(try lnRaw2(.float(m, -digits)), try ln10()), try float(.int(e + digits)))
1312 }
845 case "sin", "cos", "tan": 1313 case "sin", "cos", "tan":
846 let x = try one(args) 1314 let x = try one(args)
847 if modes.degrees, case .int(let i) = x, i % 90 == 0 { 1315 if modes.degrees, case .int(let i) = x, i % 90 == 0 {
@@ -871,6 +1339,198 @@ public enum Calc {
871 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") } 1339 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") }
872 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d) 1340 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d)
873 return try fromDouble(angle(r)) 1341 return try fromDouble(angle(r))
1342 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor":
1343 guard args.count == 2 else { throw Unsupported("arguments") }
1344 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"]
1345 return try binary(ops[name]!, args[0], args[1])
1346 case "lnot":
1347 return .int(try truth(try one(args)) ? 0 : 1)
1348 case "percent":
1349 let x = try one(args)
1350 _ = try sign(x)
1351 return try divide(x, .int(100))
1352 case "float", "pfloat":
1353 return try float(try one(args))
1354 case "sign":
1355 return .int(try sign(try one(args)))
1356 case "rounde", "roundu":
1357 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1358 let x = args[0]
1359 _ = try sign(x)
1360 guard args.count == 2 else { return try round(x, even: name == "rounde") }
1361 guard isWhole(args[1]), case let places = try trunc(args[1]) else { throw Unsupported("arguments") }
1362 if places <= 0, case .int = x { return x }
1363 let rounded = try round(try scale(x, places, fractions: true), even: name == "rounde")
1364 return try scale(rounded, -places, fractions: modes.preferFractions)
1365 case "frac":
1366 return try toFraction(try one(args))
1367 case "fdiv":
1368 guard args.count == 2 else { throw Unsupported("arguments") }
1369 func parts(_ v: Value) throws -> (Int, Int) {
1370 if isWhole(v) { return (try trunc(v), 1) }
1371 guard case .frac(let n, let d) = v else { throw Unsupported("arguments") }
1372 return (n, d)
1373 }
1374 let (n1, d1) = try parts(args[0])
1375 let (n2, d2) = try parts(args[1])
1376 guard n2 != 0 else { throw Unsupported("division by zero") }
1377 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
1378 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
1379 if o1 || o2 { throw Unsupported("integer size") }
1380 return try fraction(n, d)
1381 case "gcd":
1382 guard args.count == 2 else { throw Unsupported("arguments") }
1383 return try gcd(args[0], args[1])
1384 case "lcm":
1385 guard args.count == 2 else { throw Unsupported("arguments") }
1386 return try divide(try absolute(try multiply(args[0], args[1])), try gcd(args[0], args[1]), fractions: modes.preferFractions)
1387 case "choose", "perm":
1388 guard args.count == 2, case .int(let n) = args[0], case .int(let m) = args[1] else { throw Unsupported("arguments") }
1389 if name == "choose" { return .int(try choose(n, m)) }
1390 guard m >= 0, m <= n else { throw Unsupported("arguments") }
1391 var result = Value.int(1)
1392 for k in stride(from: n - m + 1, through: n, by: 1) { result = try multiply(result, .int(k)) }
1393 return result
1394 case "pow":
1395 guard args.count == 2 else { throw Unsupported("arguments") }
1396 return try power(args[0], args[1], fractions: modes.preferFractions)
1397 case "exp10":
1398 let x = try one(args)
1399 guard case .int(let n) = x else { throw Unsupported("arguments") }
1400 return n == 0 ? .int(1) : try makeFloat(1, n)
1401 case "nroot":
1402 guard args.count == 2, case .int(let n) = args[1], n >= 1 else { throw Unsupported("arguments") }
1403 _ = try sign(args[0])
1404 return n == 1 ? args[0] : try rootPower(args[0], n)
1405 case "hypot":
1406 guard args.count == 2 else { throw Unsupported("arguments") }
1407 let (a, b) = (args[0], args[1])
1408 _ = (try sign(a), try sign(b))
1409 if isZero(a) { return try absolute(b) }
1410 if isZero(b) { return try absolute(a) }
1411 return try extra(1) { try squareRoot(try add(try multiply(a, a), try multiply(b, b))) }
1412 case "log":
1413 guard args.count == 2 else {
1414 guard args.count == 1 else { throw Unsupported("arguments") }
1415 return try call("ln", args)
1416 }
1417 let (x, b) = (args[0], args[1])
1418 _ = (try sign(x), try sign(b))
1419 if b == .int(10) || b == .float(1, 1) { return try call("log10", [x]) }
1420 if isZero(x) || isZero(b) || b == .int(1) || b == .float(1, 0) { throw Unsupported("logarithm domain") }
1421 if x == .int(1) || x == .float(1, 0) {
1422 if case .float = b { return .float(0, 0) }
1423 return .int(0)
1424 }
1425 if rational(x) != nil, rational(b) != nil, try sign(x) > 0, try sign(b) > 0 {
1426 var sign = 1
1427 var (xx, bb) = (x, b)
1428 if try compare(.int(1), x) >= 0 {
1429 sign = -1
1430 xx = try divide(.int(1), x)
1431 }
1432 if try compare(.int(1), b) >= 0 {
1433 sign = -sign
1434 bb = try divide(.int(1), b)
1435 }
1436 let inverse = try compare(xx, bb) < 0
1437 let (exact, n) = inverse ? try integerLog(bb, xx) : try integerLog(xx, bb)
1438 if exact { return inverse ? try divide(.int(1), .int(sign * n), fractions: modes.preferFractions) : .int(sign * n) }
1439 }
1440 return try extra(2) { try divide(try lnRaw(try float(x)), try lnRaw(try float(b))) }
1441 case "sinh", "cosh":
1442 let x = try one(args)
1443 if x == .int(0) { return .int(name == "sinh" ? 0 : 1) }
1444 _ = try sign(x)
1445 return try extra(2) {
1446 let e = try expRaw(try float(x))
1447 return try multiply(try add(e, try divide(.int(name == "sinh" ? -1 : 1), e)), .float(5, -1))
1448 }
1449 case "tanh":
1450 let x = try one(args)
1451 if x == .int(0) { return x }
1452 _ = try sign(x)
1453 return try extra(2) {
1454 let e = try extra(2) { try expRaw(try float(x)) }
1455 let inverse = try divide(.int(1), e)
1456 return try divide(try subtract(e, inverse), try add(e, inverse))
1457 }
1458 case "arcsinh":
1459 let x = try one(args)
1460 if x == .int(0) { return x }
1461 _ = try sign(x)
1462 return try extra(2) { try lnRaw(try add(x, try squareRootRaw(try add(try multiply(x, x), .float(1, 0))))) }
1463 case "arccosh":
1464 let x = try one(args)
1465 if x == .int(1) { return .int(0) }
1466 guard try compare(x, .int(-1)) != 0 else { throw Unsupported("complex result") }
1467 return try extra(2) {
1468 let xp1 = try add(.int(1), x)
1469 return try lnRaw(try add(x, try multiply(xp1, try squareRootRaw(try divide(try subtract(x, .float(1, 0)), xp1)))))
1470 }
1471 case "arctanh":
1472 let x = try one(args)
1473 if x == .int(0) { return x }
1474 guard try compare(x, .int(1)) <= 0 else { throw Unsupported("complex result") }
1475 return try extra(2) {
1476 try multiply(try lnRaw(try divide(try add(.float(1, 0), x), try subtract(.int(1), x))), .float(5, -1))
1477 }
1478 case "arctan2":
1479 guard args.count == 2 else { throw Unsupported("arguments") }
1480 _ = (try sign(args[0]), try sign(args[1]))
1481 return try extra(2) {
1482 let (y, x) = (try float(args[0]), try float(args[1]))
1483 let r: Value
1484 if isZero(y) {
1485 r = try sign(x) < 0 ? try pi() : .float(0, 0)
1486 } else if isZero(x) {
1487 r = try sign(y) > 0 ? try piOver2() : try negate(try piOver2())
1488 } else if try sign(x) > 0 {
1489 r = try arctanRaw(try divide(y, x))
1490 } else if try sign(y) > 0 {
1491 r = try add(try arctanRaw(try divide(y, x)), try pi())
1492 } else {
1493 r = try subtract(try arctanRaw(try divide(y, x)), try pi())
1494 }
1495 return modes.degrees ? try divide(r, try piOver180()) : r
1496 }
1497 case "deg", "rad":
1498 let x = try one(args)
1499 _ = try sign(x)
1500 return try extra(2) { name == "deg" ? try divide(x, try piOver180()) : try multiply(x, try piOver180()) }
1501 case "vflat":
1502 return .vector(try elements(args))
1503 case "vgmean", "vhmean":
1504 let items = try elements(args)
1505 guard !items.isEmpty else { throw Unsupported("empty vector") }
1506 return try extra(2) {
1507 if name == "vhmean" {
1508 let inverses = try items.map { try divide(.int(1), $0, fractions: modes.preferFractions) }
1509 return try divide(.int(items.count), try inverses.dropFirst().reduce(inverses[0], add), fractions: modes.preferFractions)
1510 }
1511 let product = try items.dropFirst().reduce(items[0], multiply)
1512 return items.count == 2 ? try squareRoot(product) : try rootPower(product, items.count)
1513 }
1514 case "vcov", "vpcov", "vcorr":
1515 // Two vectors; one matrix argument isn't supported.
1516 guard args.count == 2 else { throw Unsupported("arguments") }
1517 return try covariance(try elements([args[0]]), try elements([args[1]]), population: name == "vpcov", correlation: name == "vcorr")
1518 case "agmean":
1519 guard args.count == 2 else { throw Unsupported("arguments") }
1520 let (a, b) = (args[0], args[1])
1521 _ = (try sign(a), try sign(b))
1522 if try compare(a, b) == 0 || isZero(a) { return a }
1523 if isZero(b) { return b }
1524 return try extra(2) {
1525 var (x, y) = (try float(try absolute(a)), try float(try absolute(b)))
1526 for _ in 0..<1000 {
1527 if nearlyEqual(x, y) { return x }
1528 let mean = try multiply(try add(x, y), .float(5, -1))
1529 y = try extra(1) { try squareRootRaw(try multiply(x, y)) }
1530 x = mean
1531 }
1532 throw Unsupported("number")
1533 }
874 default: 1534 default:
875 throw Unsupported("function \(name)") 1535 throw Unsupported("function \(name)")
876 } 1536 }
Sources/OrgCore/Compute/TableFormulas.swift +1
@@ -334,6 +334,7 @@ extension EmacsBuffer {
334 func calc(_ s: String) throws -> String { 334 func calc(_ s: String) throws -> String {
335 let text = mode.numbers ? numberText(s) : s 335 let text = mode.numbers ? numberText(s) : s
336 guard text.range(of: calcNumber, options: .regularExpression) != nil || text == "nan" 336 guard text.range(of: calcNumber, options: .regularExpression) != nil || text == "nan"
337 || text.range(of: "^[-+]?[0-9]+:[0-9:]+$", options: .regularExpression) != nil
337 || text.range(of: "^" + timestampBoth + "$", options: .regularExpression) != nil else { 338 || text.range(of: "^" + timestampBoth + "$", options: .regularExpression) != nil else {
338 throw Calc.Unsupported("non-numeric field \(text)") 339 throw Calc.Unsupported("non-numeric field \(text)")
339 } 340 }
Tests/OrgCoreTests/CalcTests.swift +164 −23
@@ -4,7 +4,7 @@ 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)]) throws -> [String] { 7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12) throws -> [String] {
8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)") 8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
10 defer { try? FileManager.default.removeItem(at: folder) } 10 defer { try? FileManager.default.removeItem(at: folder) }
@@ -25,13 +25,15 @@ enum CalcOracle {
25 (let* ((modes (copy-sequence org-calc-default-modes)) 25 (let* ((modes (copy-sequence org-calc-default-modes))
26 (format (car (read-from-string (nth 1 c))))) 26 (format (car (read-from-string (nth 1 c)))))
27 (setq modes (plist-put modes 'calc-float-format format)) 27 (setq modes (plist-put modes 'calc-float-format format))
28 (let ((r (calc-eval (cons (car c) modes) nil))) 28 (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC"))))
29 (let ((r (condition-case e (calc-eval (cons (car c) modes) nil)
30 (error (format "LISP ERROR %S" e)))))
29 (if (stringp r) r (format "ERROR %S" r))))) 31 (if (stringp r) r (format "ERROR %S" r)))))
30 cases))) 32 cases)))
31 (with-temp-file (getenv "ORACLE_OUTPUT") 33 (with-temp-file (getenv "ORACLE_OUTPUT")
32 (insert (json-encode (vconcat results))))) 34 (insert (json-encode (vconcat results)))))
33 """#.write(to: script, atomically: true, encoding: .utf8) 35 """#.write(to: script, atomically: true, encoding: .utf8)
34 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path]) 36 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision)])
35 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output)) 37 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
36 } 38 }
37} 39}
@@ -64,28 +66,73 @@ struct CalcTests {
64 "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)", 66 "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)",
65 ] 67 ]
66 68
67 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 69 /// Constants, functions and syntax that only some tables use.
68 func matchesCalc() throws { 70 static let functions = [
69 var cases = Self.fixed.map { ($0, "(float 8)") } 71 // Grammar: juxtaposition, percent, factorials, fractions and radix integers.
70 for format in ["(float 3)", "(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] { 72 "2 3", "2 (3)", "(2)(3)", "2 3 4", "2 3+4", "2*3 4", "-2 3", "2 -3", "2 (3) + 1", "2 .5", "1.5 2", "2 nan", "6/2 3",
71 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) } 73 "5%", "50%*20", "5%+1", "5%3", "5% 3", "(5)%", "12.5%", "1:4%", "100%", "-5%", "2^50%", "5%-1", "5% (2)",
72 } 74 "5!", "5!+1", "-5!", "0!", "(3)!", "2^3!", "3!!", "6!!", "0!!", "1!!", "5.!", "20.!", "3! 2", "5! == 120", "5!=120",
73 // Generated: random operands and operators. 75 "1:3", "2:4", "4:2", "-1:3", "1:2:3", "1:0:3", "0:5", "1:3+1", "1:3*0.5", "1:3*3", "2:3^2", "(1:3)",
74 var generator = SystemRandomNumberGenerator() 76 "16#FF", "16#ff", "16#FF+1", "2#101", "8#17", "36#Z", "36#zz", "016#10", "10#99",
75 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2"] 77 // Comparisons and logic as functions; `&&` and `||` give an argument.
76 let ops = ["+", "-", "*", "/"] 78 "eq(2,2)", "eq(2,2.0)", "neq(1,2)", "lt(1,2)", "gt(1,2)", "leq(2,2)", "geq(1,2)", "lt(1:3,0.5)",
77 for _ in 0..<300 { 79 "land(2,3)", "land(0,3)", "lor(0,2.5)", "lor(3,0)", "lnot(0)", "lnot(2.5)", "2 && 3", "0 || 2.5", "1.5 && 0.",
78 var e = numbers.randomElement(using: &generator)! 80 "0. || 0", "if(1:2, 1, 2)",
79 for _ in 0..<Int.random(in: 1...4, using: &generator) { 81 // Statistics.
80 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))" 82 "vsum([1,2],[3,4])", "vsum(1,2,3)", "vsum([1,2],3)", "vsum()", "vsum([[1,2],[3]])", "vmax([1,2],[5,3])",
81 } 83 "vmax(1,7,3)", "vmin([1,2],[0,3])", "vmean([1,2],[3])", "vmean(1,2)", "vprod([1,2],[3])", "vcount([1,2],3)",
82 cases.append((e, "(float 8)")) 84 "vcount()", "vmedian([1,2],[5])", "vvar([1,2],[3])", "vsdev(1,2,3)", "vpsdev([1,2],[3,4])", "vmax(5)",
83 } 85 "vmean(5)", "vsum(vflat([1,[2,3]],4))", "vcount(vflat(1,2,3))", "vgmean([1,2,4])", "vgmean([2,8])",
84 let emacs = try CalcOracle.run(cases) 86 "vgmean([1,2,3])", "vgmean([1.5,2.5])", "vgmean([1:2,2])", "vgmean([0,2])", "vgmean([5])", "vgmean([2,3,4,5])",
87 "vgmean([1,2,3,4,5,6,7,8,9,10,11,12])", "vgmean([1.5,2,2.5,3,3.5])", "vgmean([16,1,1,1])", "vgmean([1:8,1,1])",
88 "vhmean([1,2,4])", "vhmean([1,2])", "vhmean([1.5,2.5])", "vhmean([3])", "vhmean(1,2,3)",
89 "vcov([1,2,3],[1,2,4])", "vpcov([1,2,3],[1,2,4])", "vcorr([1,2,3],[1,2,4])", "vcorr([1,2,3],[3,2,1])",
90 "vcov([1.5,2.5,4],[2,3.5,1])", "vpcov([5],[7])", "vcorr([1,2,3,4],[2,4,5,9])", "vcov([1:2,1,2],[1,2,3])",
91 "agmean(1,2)", "agmean(1,4)", "agmean(2,2)", "agmean(1.5,2)", "agmean(0,3)", "agmean(-1,4)", "agmean(24,6)",
92 // Rounding and fractions.
93 "rounde(2.5)", "rounde(3.5)", "rounde(-2.5)", "rounde(-3.5)", "rounde(2.6)", "rounde(7)", "rounde(5:2)",
94 "rounde(7:2)", "rounde(2.45,1)", "rounde(2.55,1)", "rounde(1234,-2)", "rounde(1250,-2)", "rounde(1:8,2)",
95 "roundu(2.5)", "roundu(-2.5)", "roundu(-2.4)", "roundu(2.45,1)", "roundu(-2.45,1)", "roundu(-5:2)", "roundu(3.)",
96 "fdiv(7,2)", "fdiv(6,3)", "fdiv(1:2,3)", "fdiv(3,1:2)", "fdiv(2:3,4:5)", "fdiv(7.,2)", "fdiv(-7,2)",
97 "frac(2.75)", "frac(-2.75)", "frac(7)", "frac(7:2)", "frac(7.)", "frac(0.1)", "frac(0.333333333333)",
98 "frac(3.14159265359)", "frac(1.5e-3)", "frac(0.142857142857)", "frac(1.5e-11)",
99 "sign(-3)", "sign(0)", "sign(2.5)", "sign(-1:3)", "sign(0.)",
100 "gcd(12,18)", "gcd(-12,18)", "gcd(0,5)", "gcd(12.,18)", "gcd(1:2,1:3)", "gcd(2:3,4)", "gcd(-1:2,3:4)", "gcd(0,0)",
101 "lcm(4,6)", "lcm(-4,6)", "lcm(0,6)", "lcm(1:2,1:3)", "lcm(3,4)",
102 "choose(5,2)", "choose(5,0)", "choose(5,6)", "choose(-5,2)", "choose(-5,3)", "choose(-3,-5)", "choose(-5,-3)",
103 "choose(5,-1)", "choose(52,5)", "choose(60,30)", "perm(5,2)", "perm(5,0)", "perm(5,5)", "perm(20,10)",
104 // Powers, roots and logarithms.
105 "pow(2,10)", "pow(2,0.5)", "pow(2,-1)", "8^(1:3)", "pow(8,1:3)", "4^(3:2)", "pow(4,3:2)", "27^(2:3)", "8^(-1:3)",
106 "2^(1:3)", "2^(1:4)", "16^(3:4)", "2^(2:7)", "2^(1:11)", "1.5^(1:3)", "2^1.5", "2^2.5", "2^0.25", "2^-0.5", "2^2.",
107 "3^2.", "10^2.", "10.^3", "10.^-2.", "0^2", "0^2.", "0.^0", "1:4^(1:2)", "(1:8)^(2:3)", "2^1.1", "0.5^0.75", "exp10(2)", "exp10(-2)", "exp10(0)", "exp10(15)",
108 "nroot(8,3)", "nroot(27,3)", "nroot(10,3)", "nroot(16,4)", "nroot(2.5,2)", "nroot(1:8,3)", "nroot(-8,1)",
109 "nroot(2,4)", "nroot(2,5)", "nroot(100,7)", "nroot(1000,12)", "nroot(3.5,11)", "nroot(2:3,3)", "nroot(0,3)",
110 "nroot(1,5)", "nroot(1024,10)", "nroot(7,6)", "nroot(1e10,9)",
111 "hypot(3,4)", "hypot(1,1)", "hypot(1.5,2)", "hypot(-3,4)", "hypot(0,-2.5)", "hypot(1:3,1:4)", "hypot(5,12)",
112 "log(8,2)", "log(100,10)", "log(10,2)", "log(2.5,1.5)", "log(1,2)", "log(9,3)", "log(1:8,2)", "log(2,8)",
113 "log(8,1:2)", "log(1:4,1:2)", "log(1000,10.)", "log(1.,3)", "log(1,2.)", "log(27,1:3)", "log(10,3)", "log(5)",
114 "log(0.5,2)", "log(81,9)", "log(3,81)", "log(1.25,10)", "log10(1.25)", "log10(5:4)", "log10(1:100)", "log10(0.001)",
115 "log10(7.5e-8)", "log10(99)", "log10(2:3)",
116 // Hyperbolic and angle functions.
117 "sinh(1)", "sinh(0)", "sinh(-2.5)", "sinh(0.)", "sinh(1:2)", "cosh(1)", "cosh(0)", "cosh(-0.5)", "tanh(1)",
118 "tanh(0)", "tanh(-3)", "tanh(0.25)", "arcsinh(1)", "arcsinh(0)", "arcsinh(-2.5)", "arcsinh(1:2)",
119 "arccosh(2)", "arccosh(1)", "arccosh(1.)", "arccosh(10.5)", "arctanh(0.5)", "arctanh(0)", "arctanh(-0.25)",
120 "arctanh(1:3)", "arctan2(1,1)", "arctan2(1,0)", "arctan2(0,-1)", "arctan2(-1,-1)", "arctan2(0,0)",
121 "arctan2(1,2)", "arctan2(0,1)", "arctan2(-1,0)", "arctan2(3,-4)", "arctan2(-2.5,1)",
122 "deg(1)", "deg(3.14159)", "deg(1:2)", "rad(180)", "rad(90)", "rad(1)", "rad(-45.5)",
123 "float(7)", "float(7:2)", "float(2.5)", "pfloat(7)", "float(1:3)", "float(123456789012345)",
124 "sqrt(2)", "sqrt(1e6)", "sqrt(10)", "sqrt(2:9)", "sqrt(0.5)", "sqrt(99999999)",
125 ]
126
127 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
128 /// cases `Calc.evaluate` doesn't support.
129 static func compare(_ cases: [(String, String)], precision: Int = 12) throws -> [String] {
130 let emacs = try CalcOracle.run(cases, precision: precision)
85 #expect(emacs.count == cases.count) 131 #expect(emacs.count == cases.count)
86 var skipped: [String] = [] 132 var skipped: [String] = []
87 for (c, expected) in zip(cases, emacs) { 133 for (c, expected) in zip(cases, emacs) {
88 var modes = Calc.Modes() 134 var modes = Calc.Modes()
135 modes.precision = precision
89 let f = c.1.dropFirst().dropLast().split(separator: " ") 136 let f = c.1.dropFirst().dropLast().split(separator: " ")
90 let n = Int(f[1])! 137 let n = Int(f[1])!
91 switch f[0] { 138 switch f[0] {
@@ -100,15 +147,109 @@ struct CalcTests {
100 skipped.append(c.0) 147 skipped.append(c.0)
101 continue 148 continue
102 } 149 }
103 #expect(ours == expected, "\(c.0) \(c.1)") 150 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)")
151 }
152 return skipped
153 }
154
155 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
156 func matchesCalc() throws {
157 var cases = Self.fixed.map { ($0, "(float 8)") }
158 for format in ["(float 3)", "(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
159 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) }
160 }
161 // Generated: random operands and operators.
162 var generator = SystemRandomNumberGenerator()
163 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2"]
164 let ops = ["+", "-", "*", "/"]
165 for _ in 0..<300 {
166 var e = numbers.randomElement(using: &generator)!
167 for _ in 0..<Int.random(in: 1...4, using: &generator) {
168 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
169 }
170 cases.append((e, "(float 8)"))
104 } 171 }
105 // Only what Calc itself can't show as a number. 172 // Only what Calc itself can't show as a number.
173 let skipped = try Self.compare(cases)
106 #expect(skipped == [], "\(skipped)") 174 #expect(skipped == [], "\(skipped)")
107 } 175 }
108 176
177 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
178 func functionsMatchCalc() throws {
179 var cases = Self.functions.map { ($0, "(float 12)") }
180 let sample = ["vgmean([1,2,3])", "agmean(1,2)", "sinh(1)", "arctan2(1,2)", "frac(0.1)", "log(10,2)", "nroot(10,3)",
181 "vcorr([1,2,3],[1,2,4])", "5%", "1:3*3", "rounde(2.45,1)", "hypot(1,1)", "rad(1)", "16#FF/7"]
182 for format in ["(float 8)", "(fix 2)", "(sci 3)", "(eng 2)"] {
183 for e in sample { cases.append((e, format)) }
184 }
185 // Generated: functions of random integers, fractions and floats. Arguments outside a
186 // function's domain are refused, so only what is computed is compared.
187 var generator = SystemRandomNumberGenerator()
188 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "1:3", "5:4", "2.5e-2"]
189 let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
190 let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
191 for _ in 0..<200 {
192 let x = numbers.randomElement(using: &generator)!
193 let y = numbers.randomElement(using: &generator)!
194 cases.append(("\(unary.randomElement(using: &generator)!)(\(x))", "(float 12)"))
195 cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
196 cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
197 }
198 let skipped = Set(try Self.compare(cases)).intersection(Self.functions + sample)
199 #expect(skipped == [], "\(skipped)")
200 }
201
202 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
203 func precisionMatchesCalc() throws {
204 var generator = SystemRandomNumberGenerator()
205 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2",
206 "1.23456789012345678", "123456789.987654321"]
207 let ops = ["+", "-", "*", "/"]
208 for precision in [3, 6, 15, 18] {
209 var cases = ["1/3", "2/3", "1/7", "1.23456789012345678", "round(2/3,2)", "rounde(2.45,1)", "frac(0.1)", "1:3+0.5",
210 "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
211 // Two digits more must fit in 18.
212 if precision <= 16 {
213 cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])", "0.7^-3"].map { ($0, "(float 0)") }
214 }
215 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
216 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
217 if precision <= 14 {
218 cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5",
219 "exp(1.58)", "ln(9.44)", "0.08^1.5", "0.11^1.5", "exp(8.44)", "pow(2.5,1:3)"].map { ($0, "(float 0)") }
220 // exp, ln and powers round at two digits more first.
221 for _ in 0..<150 {
222 let x = "\(Int.random(in: 1...999, using: &generator))e-2"
223 let y = ["1.5", "0.5", "2.5", "1:3", "0.25", "-1.5", "2.", "3.7", "1.1", "-0.75", "5:7", "1:12"].randomElement(using: &generator)!
224 cases += [("exp(\(x))", "(float 0)"), ("ln(\(x))", "(float 0)"), ("(\(x))^(\(y))", "(float 0)")]
225 }
226 }
227 for _ in 0..<100 {
228 var e = numbers.randomElement(using: &generator)!
229 for _ in 0..<Int.random(in: 1...3, using: &generator) {
230 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
231 }
232 cases.append((e, "(float 0)"))
233 }
234 let skipped = try Self.compare(cases, precision: precision)
235 #expect(skipped == [], "p\(precision) \(skipped)")
236 }
237 }
238
109 @Test func unsupported() { 239 @Test func unsupported() {
110 for e in ["abc*2", "1/0", "vmean([])", "pi", "5%", "(-8)^(1/3)", "2 3", "vvar([5])", "1<2<3"] { 240 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3",
241 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
242 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
243 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4",
244 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
245 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
246 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "0^-1", "0^0.", "ln(0)", "ln(-1)"] {
111 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) } 247 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
112 } 248 }
249 var modes = Calc.Modes()
250 modes.precision = 15
251 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
252 modes.precision = 19
253 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
113 } 254 }
114} 255}
Tests/OrgCoreTests/TableFormulaTests.swift +1
@@ -31,6 +31,7 @@ struct TableFormulaTests {
31 /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and 31 /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and
32 /// the rest that once needed Emacs: all run natively. 32 /// the rest that once needed Emacs: all run natively.
33 static let native = [ 33 static let native = [
34 "| a | b | c | d | mean | ratio | gmean | more |\n|---+---+---+---+------+-------+-------+------|\n| 1:30 | 2 | 3 | 4.5 | | | | |\n| 2:4 | 5 | 1 | 2 | | | | |\n#+TBLFM: $5=vmean($2..$3,$4)::$6=$2/$3;p15::$7=vgmean($2..$4);f3::$8=$4% + $1 2 + roundu($4) + hypot($2,$3)\n",
34 "| a | b |\n|---+---|\n| hello | |\n| x \"q\" | |\n| | |\n#+TBLFM: $2='(concat $1 \"!\")\n", 35 "| a | b |\n|---+---|\n| hello | |\n| x \"q\" | |\n| | |\n#+TBLFM: $2='(concat $1 \"!\")\n",
35 "| a | b |\n|---+---|\n| 1 | |\n| 2.5 | |\n| x | |\n#+TBLFM: $2='(* 2 $1);N\n", 36 "| a | b |\n|---+---|\n| 1 | |\n| 2.5 | |\n| x | |\n#+TBLFM: $2='(* 2 $1);N\n",
36 "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n| 3 | 4 | |\n#+TBLFM: $3='(+ $1 $2);L\n", 37 "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n| 3 | 4 | |\n#+TBLFM: $3='(+ $1 $2);L\n",
docs/manual/guide/10-tables.org +43 −15
@@ -231,9 +231,9 @@ In a Calc formula a single field becomes a number in parentheses, and a range be
231a vector such as =[1,2,3]=. Without the =E= flag, empty fields count as 0 on their own 231a vector such as =[1,2,3]=. Without the =E= flag, empty fields count as 0 on their own
232and are left out of ranges. 232and are left out of ranges.
233 233
234Fields in a Calc formula must hold numbers, timestamps or =nan=, unless the =N= flag 234Fields in a Calc formula must hold numbers, fractions such as =1:30=, timestamps or
235reads every field as a number. A reference to a field with other text needs Emacs, 235=nan=, unless the =N= flag reads every field as a number. A reference to a field with
236because Calc would treat the text as a symbol. 236other text needs Emacs, because Calc would treat the text as a symbol.
237 237
238** Names, parameters and constants 238** Names, parameters and constants
239 239
@@ -311,22 +311,25 @@ Calc formulas use Calc's number rules: integers are exact, and decimal numbers a
311rounded to 12 significant digits after every operation. Results are shown with up to 311rounded to 12 significant digits after every operation. Results are shown with up to
3128 significant digits unless a format flag says otherwise (=org-calc-default-modes=). 3128 significant digits unless a format flag says otherwise (=org-calc-default-modes=).
313 313
314Operators, from lowest to highest precedence (the lowest, ~||~, is logical or, giving 314Operators, from lowest to highest precedence (the lowest, ~||~, is logical or: the left
3151 or 0): 315side if it is nonzero, else the right side):
316 316
317| Operator | Meaning | 317| Operator | Meaning |
318|------------------------------------+-----------------------------------------------------------| 318|------------------------------------+-----------------------------------------------------------|
319| =&&= | Logical and. | 319| =&&= | Logical and: the left side if it is zero, else the right side. |
320| =!= | Logical not. | 320| =!= | Logical not. |
321| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. | 321| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. |
322| =+=, =-= | Addition and subtraction. | 322| =+=, =-= | Addition and subtraction. |
323| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. | 323| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. |
324| =*= | Multiplication. | 324| =*= | Multiplication. Values side by side also multiply: =2 3=, =2 (x)=. |
325| unary =-= | Negation. | 325| unary =-= | Negation. |
326| =^= | Power. | 326| =^= | Power. |
327| =!=, =!!= after a value | Factorial, double factorial. |
328| =%= after a value | Percent: =5%= is =0.05=. Followed by a value, =%= is modulo instead. |
327 329
328Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and 330Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and
329=nan= is "not a number". 331=nan= is "not a number". =1:3= writes the fraction one third and =1:2:3= one and two
332thirds; =16#FF= writes an integer in base 16 (any base from 2 to 36).
330 333
331Functions: 334Functions:
332 335
@@ -335,22 +338,42 @@ Functions:
335| =vsum=, =vprod= | Sum or product of a vector. | 338| =vsum=, =vprod= | Sum or product of a vector. |
336| =vcount= | Number of elements. | 339| =vcount= | Number of elements. |
337| =vmean=, =vmedian= | Mean, median. | 340| =vmean=, =vmedian= | Mean, median. |
341| =vgmean=, =vhmean= | Geometric mean, harmonic mean. |
338| =vmax=, =vmin= | Largest, smallest element. | 342| =vmax=, =vmin= | Largest, smallest element. |
339| =vvar=, =vsdev= | Sample variance, sample standard deviation. | 343| =vvar=, =vsdev= | Sample variance, sample standard deviation. |
340| =vpvar=, =vpsdev= | Population variance, population standard deviation. | 344| =vpvar=, =vpsdev= | Population variance, population standard deviation. |
345| =vcov(x, y)=, =vpcov(x, y)=, =vcorr(x, y)= | Sample and population covariance, correlation coefficient. |
346| =vflat= | The arguments as one vector. |
347| =agmean(a, b)= | Arithmetic-geometric mean. |
341| =max(a, b, …)=, =min(a, b, …)= | Largest, smallest argument. | 348| =max(a, b, …)=, =min(a, b, …)= | Largest, smallest argument. |
342| =if(c, a, b)= | =a= if =c= is nonzero, else =b=. | 349| =if(c, a, b)= | =a= if =c= is nonzero, else =b=. |
343| =abs= | Absolute value. | 350| =abs= | Absolute value. |
344| =floor=, =ceil=, =trunc= | Round down, up, toward zero, to an integer. | 351| =floor=, =ceil=, =trunc= | Round down, up, toward zero, to an integer. |
345| =round(x)=, =round(x, n)= | Round to an integer, or to /n/ decimal places. | 352| =round(x)=, =round(x, n)= | Round to an integer, or to /n/ decimal places. |
353| =rounde=, =roundu= | As =round=, with halves going to even, or up. |
354| =frac(x)= | The fraction nearest to /x/. |
355| =fdiv(a, b)= | /a/ divided by /b/ as a fraction. |
356| =float(x)=, =pfloat(x)= | /x/ as a decimal number. |
357| =sign= | -1, 0 or 1. |
346| =mod(a, b)=, =idiv(a, b)= | As =%= and =\=. | 358| =mod(a, b)=, =idiv(a, b)= | As =%= and =\=. |
347| =fact= | Factorial of a non-negative integer. | 359| =gcd(a, b)=, =lcm(a, b)= | Greatest common divisor, least common multiple. |
360| =fact=, =dfact= | Factorial and double factorial of a non-negative integer. |
361| =choose(n, m)=, =perm(n, m)= | Binomial coefficient and permutations, of integers. |
348| =sqrt=, =exp=, =ln=, =log10= | Square root, exponential, natural and base-10 logarithm. | 362| =sqrt=, =exp=, =ln=, =log10= | Square root, exponential, natural and base-10 logarithm. |
363| =log(x, b)= | Logarithm of /x/ to base /b/. |
364| =pow(x, y)=, =nroot(x, n)=, =exp10(n)= | /x/ to the power /y/, /n/-th root, 10 to an integer power. |
365| =hypot(a, b)= | The square root of /a/² + /b/². |
349| =sin=, =cos=, =tan= | Trigonometry, in degrees unless the =R= flag is set. | 366| =sin=, =cos=, =tan= | Trigonometry, in degrees unless the =R= flag is set. |
350| =arcsin=, =arccos=, =arctan= | Inverse trigonometry, in degrees unless =R=. | 367| =arcsin=, =arccos=, =arctan=, =arctan2(y, x)= | Inverse trigonometry, in degrees unless =R=. |
368| =sinh=, =cosh=, =tanh= | Hyperbolic functions. |
369| =arcsinh=, =arccosh=, =arctanh= | Inverse hyperbolic functions. |
370| =deg=, =rad= | Radians to degrees, degrees to radians. |
371| =eq=, =neq=, =lt=, =gt=, =leq=, =geq= | As ~==~, ~!=~, =<=, =>=, ~<=~ and ~>=~. |
372| =land=, =lor=, =lnot= | As =&&=, ~||~ and =!=. |
351 373
352Other Calc functions, variables such as =pi= or =e=, symbolic results, complex results 374The statistics functions take any number of vectors and numbers, as in
353and division by zero need Emacs. 375=vmean($2..$4, $6)=. Other Calc functions, variables such as =pi= or =e= (which Calc
376keeps as symbols), symbolic results, complex results and division by zero need Emacs.
354 377
355** Mode flags and formats 378** Mode flags and formats
356 379
@@ -362,7 +385,7 @@ After the formula, a =;= starts its flags, as in ~$3=$1/$2;%.2f~ or ~$4=$1*2;f2~
362| =fN= | Fixed format with /N/ decimal places. | 385| =fN= | Fixed format with /N/ decimal places. |
363| =sN= | Scientific format with /N/ digits. | 386| =sN= | Scientific format with /N/ digits. |
364| =eN= | Engineering format with /N/ digits. | 387| =eN= | Engineering format with /N/ digits. |
365| =pN= | Calc precision. Only =p12=, the default, is evaluated natively; others need Emacs. | 388| =pN= | Calc precision, 3 to 18 digits (12 by default). See below for limits. |
366| =D=, =R= | Angles in degrees (the default) or radians. | 389| =D=, =R= | Angles in degrees (the default) or radians. |
367| =F= | Prefer fractions: =1/3= stays =1:3=. | 390| =F= | Prefer fractions: =1/3= stays =1:3=. |
368| =N= | Treat every field as a number; text counts as 0. | 391| =N= | Treat every field as a number; text counts as 0. |
@@ -372,6 +395,10 @@ After the formula, a =;= starts its flags, as in ~$3=$1/$2;%.2f~ or ~$4=$1*2;f2~
372| =U= | As =T=, showing =HH:MM=. | 395| =U= | As =T=, showing =HH:MM=. |
373| =t= | As =T=, showing decimal hours with two places, such as =1.50=. | 396| =t= | As =T=, showing decimal hours with two places, such as =1.50=. |
374 397
398Above =p14=, functions worked out from decimal approximations (=sqrt= of a non-square,
399=exp=, =ln=, =log=, non-integer powers, trigonometric and hyperbolic functions) may need
400Emacs, and above =p16= so may the statistics functions and powers of decimal numbers.
401
375The flags =S= (symbolic) and =u= need Emacs. Any other text after the flags is a 402The flags =S= (symbolic) and =u= need Emacs. Any other text after the flags is a
376=format= string applied to the result, such as =%.2f= or =%d=; =format= supports 403=format= string applied to the result, such as =%.2f= or =%d=; =format= supports
377=%s=, =%S=, =%d=, =%o=, =%x=, =%X=, =%c=, =%e=, =%f= and =%g=. 404=%s=, =%S=, =%d=, =%o=, =%x=, =%X=, =%c=, =%e=, =%f= and =%g=.
@@ -515,8 +542,9 @@ When a formula uses something the native evaluator doesn't have, the command rep
515what it was and the Mac recalculates the table in Emacs instead. This happens for: 542what it was and the Mac recalculates the table in Emacs instead. This happens for:
516 543
517- references to fields holding text in a Calc formula, and symbolic results; 544- references to fields holding text in a Calc formula, and symbolic results;
518- Calc functions and variables not listed above, precision other than =p12=, and the 545- Calc functions and variables not listed above, intervals such as =[1..5]=,
519 =S= and =u= flags; 546 precisions beyond those given under /Mode flags and formats/, and the =S= and =u=
547 flags;
520- division by zero, complex results, vector results, and numbers too large for 548- division by zero, complex results, vector results, and numbers too large for
521 64-bit integers; 549 64-bit integers;
522- Lisp functions not listed above. 550- Lisp functions not listed above.