Commit 24b578029b

24b578029b77ce5b2aeb963d1efc8106b746653d

parent: 604330cd4d

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 16:37 UTC

Calc: precision modes, fractions, percent, factorial, radix, juxtaposition and more functions

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +697 −85
@@ -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.
@@ -306,6 +399,262 @@ public enum Calc {
306 return m == 0 ? 0 : (m < 0 ? -1 : 1) 399 return m == 0 ? 0 : (m < 0 ? -1 : 1)
307 } 400 }
308 401
402 static func absolute(_ v: Value) throws -> Value { try sign(v) < 0 ? try negate(v) : v }
403
404 /// `math-floor` of a real number, as an integer.
405 static func floorInt(_ v: Value) throws -> Int {
406 let t = try trunc(v)
407 return try sign(v) < 0 && compare(v, .int(t)) != 0 ? t - 1 : t
408 }
409
410 // MARK: - Roots, logarithms and rounding
411
412 /// `math-sqrt` of a real number.
413 static func squareRoot(_ a: Value) throws -> Value {
414 if isZero(a) { return a }
415 guard try sign(a) > 0 else { throw Unsupported("complex result") }
416 func exact(_ i: Int) -> Int? {
417 let guess = Int(Double(i).squareRoot())
418 return [guess - 1, guess, guess + 1].first { $0 >= 0 && $0.multipliedReportingOverflow(by: $0) == (i, false) }
419 }
420 if case .int(let i) = a, let root = exact(i) { return .int(root) }
421 if case .frac(let n, let d) = a, let rn = exact(n), let rd = exact(d) { return .frac(rn, rd) }
422 let x = try float(a)
423 return try extra(1) { try squareRootRaw(x) }
424 }
425
426 /// `math-sqrt-raw` of a float.
427 static func squareRootRaw(_ a: Value) throws -> Value {
428 if isZero(a) { return a }
429 guard try sign(a) > 0 else { throw Unsupported("complex result") }
430 return try emacs({ $0.squareRoot() }, a)
431 }
432
433 /// `math-exp-raw` of a float.
434 static func expRaw(_ x: Value) throws -> Value {
435 isZero(x) ? .float(1, 0) : try emacs({ Foundation.exp($0) }, x)
436 }
437
438 /// `math-ln-raw` of a float.
439 static func lnRaw(_ x: Value) throws -> Value {
440 if x == .float(1, 0) { return .float(0, 0) }
441 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
442 return try emacs({ Foundation.log($0) }, x)
443 }
444
445 /// `math-arctan-raw` of a float.
446 static func arctanRaw(_ x: Value) throws -> Value {
447 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) }
448 return isZero(x) ? x : try emacs({ Foundation.atan($0) }, x)
449 }
450
451 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) }
452 static func ln10() throws -> Value { try makeFloat(230258509299404568401799145468436421, -35) }
453
454 /// `math-ln-raw-2`: the logarithm of a positive float by Calc's series.
455 static func lnRaw2(_ x: Value) throws -> Value {
456 if try compare(.float(14, -1), x) < 0 { return try add(try lnRaw2(try multiply(x, .float(5, -1))), try ln2()) }
457 let y = try divide(try subtract(x, .float(1, 0)), try add(x, .float(1, 0)))
458 let square = try multiply(y, y)
459 var (sum, power, n) = (y, y, 3)
460 for _ in 0..<10000 {
461 power = try multiply(power, square)
462 let next = try add(sum, try divide(power, try float(.int(n))))
463 if nearlyEqual(sum, next) { return try multiply(sum, .float(2, 0)) }
464 (sum, n) = (next, n + 2)
465 }
466 throw Unsupported("number")
467 }
468
469 /// `math-nth-root-integer`: the integer root rounded down, and whether it is exact.
470 static func integerRoot(_ a: Int, _ n: Int) throws -> (Bool, Int) {
471 let a = Int128(a)
472 var guess = try power10((digits(a) + n - 1) / n)
473 while true {
474 var p: Int128 = 1
475 for _ in 0..<(n - 1) {
476 let (r, overflow) = p.multipliedReportingOverflow(by: guess)
477 if overflow { throw Unsupported("integer size") }
478 p = r
479 }
480 let (q, r) = a.quotientAndRemainder(dividingBy: p)
481 let (g2, r2) = (q + Int128(n - 1) * guess).quotientAndRemainder(dividingBy: Int128(n))
482 if g2 < guess {
483 guess = g2
484 continue
485 }
486 return (g2 == guess && r == 0 && r2 == 0, Int(guess))
487 }
488 }
489
490 /// `math-nth-root-float`: Newton's method at one digit more.
491 static func floatRoot(_ a: Value, _ n: Int, guess: Value? = nil) throws -> Value {
492 try extra(1) {
493 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
494 let nf = try makeFloat(Int128(n), 0)
495 let nfm1 = try makeFloat(Int128(n - 1), 0)
496 var g = try guess ?? makeFloat(1, (digits(Int128(m)) + e + n / 2) / n)
497 for _ in 0..<1000 {
498 let g2 = try divide(try add(try multiply(nfm1, g), try divide(a, try integerPower(g, n - 1))), nf)
499 if nearlyEqual(g2, g) { return g2 }
500 g = g2
501 }
502 throw Unsupported("number")
503 }
504 }
505
506 /// `math-nth-root` of a positive real number.
507 static func nthRoot(_ a: Value, _ n: Int) throws -> Value {
508 switch a {
509 case .int(let i):
510 let (exact, root) = try integerRoot(i, n)
511 return exact ? .int(root) : try floatRoot(try float(a), n, guess: try float(.int(root)))
512 case .frac(let num, let den):
513 let (e1, r1) = try integerRoot(num, n)
514 let (e2, r2) = try integerRoot(den, n)
515 if e1 && e2 { return .frac(r1, r2) }
516 return try floatRoot(try float(a), n, guess: try divide(try float(.int(r1)), try float(.int(r2))))
517 default:
518 return try floatRoot(a, n)
519 }
520 }
521
522 /// `math-pow` of a real number to the power `1:n`.
523 static func rootPower(_ a: Value, _ n: Int) throws -> Value {
524 if isZero(a) || a == .int(1) || a == .float(1, 0) { return a }
525 guard try sign(a) > 0 else { throw Unsupported("complex result") }
526 switch n {
527 case 1: return a
528 case 2: return try squareRoot(a)
529 case 4: return try squareRoot(try squareRoot(a))
530 case 3...10: return try nthRoot(a, n)
531 default: return try extra(2) { try expRaw(try float(try multiply(.frac(1, n), try lnRaw(try float(a))))) }
532 }
533 }
534
535 /// `math-integer-log`: the largest n with b^n at most x, and whether b^n is x.
536 static func integerLog(_ x: Value, _ b: Value) throws -> (Bool, Int) {
537 var pows = [b]
538 var pow = try multiply(b, b)
539 while try compare(x, pow) >= 0 {
540 pows.insert(pow, at: 0)
541 pow = try multiply(pow, pow)
542 }
543 var n = 1 << (pows.count - 1)
544 var sum = n
545 pow = pows[0]
546 var rest = pows.dropFirst()
547 while let next = rest.first, try compare(pow, x) < 0 {
548 rest = rest.dropFirst()
549 n /= 2
550 let candidate = try multiply(pow, next)
551 if try compare(x, candidate) >= 0 {
552 pow = candidate
553 sum += n
554 }
555 }
556 return (pow == x, sum)
557 }
558
559 /// `math-round` in `math-rounding-mode` `even` or `up`.
560 static func round(_ a: Value, even: Bool) throws -> Value {
561 if isWhole(a) { return .int(try trunc(a)) }
562 if try sign(a) < 0, even { return try negate(try round(try negate(a), even: even)) }
563 let b = try add(a, rational(a) != nil ? .frac(1, 2) : .float(5, -1))
564 var f = try floorInt(b)
565 if even, isWhole(b), f % 2 != 0 { f -= 1 }
566 return .int(f)
567 }
568
569 /// `calcFunc-scf`: `x` times 10^n.
570 static func scale(_ x: Value, _ n: Int, fractions: Bool) throws -> Value {
571 if n == 0 { return x }
572 guard abs(n) <= 18 else { throw Unsupported("number size") }
573 let p = Int(try power10(abs(n)))
574 switch x {
575 case .int: return n > 0 ? try multiply(x, .int(p)) : try divide(x, .int(p), fractions: fractions)
576 case .frac(let a, let b):
577 let (num, o1) = a.multipliedReportingOverflow(by: n > 0 ? p : 1)
578 let (den, o2) = b.multipliedReportingOverflow(by: n > 0 ? 1 : p)
579 if o1 || o2 { throw Unsupported("integer size") }
580 return try fraction(num, den)
581 case .float(let m, let e): return try makeFloat(Int128(m), e + n)
582 default: throw Unsupported("arguments")
583 }
584 }
585
586 /// `calcFunc-frac`: the fraction closest to a float within its precision.
587 static func toFraction(_ a: Value) throws -> Value {
588 if rational(a) != nil { return a }
589 if isWhole(a) { return .int(try trunc(a)) }
590 if try sign(a) < 0 { return try negate(try toFraction(try negate(a))) }
591 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
592 let tolerance = Value.float(5, digits(Int128(m)) + e - (1 + precision))
593 /// `math-eval-continued-fraction`.
594 func evaluate(_ terms: [Int], fractions: Bool) throws -> Value {
595 var n = Value.int(terms.last!)
596 var d = Value.int(1)
597 for c in terms.reversed().dropFirst() { (n, d) = (try add(try multiply(.int(c), n), d), n) }
598 return try divide(n, d, fractions: fractions)
599 }
600 let terms = try $precision.withValue(precision + 2) {
601 var terms: [Int] = []
602 var aa = a
603 while try terms.isEmpty || (!isZero(aa) && compare(try absolute(try subtract(a, try evaluate(terms, fractions: false))), tolerance) >= 0) {
604 guard terms.count < 100 else { throw Unsupported("number") }
605 let whole = try trunc(aa)
606 aa = try subtract(aa, .int(whole))
607 terms.append(whole)
608 if !isZero(aa) { aa = try divide(.int(1), aa) }
609 }
610 return terms
611 }
612 return try evaluate(terms, fractions: true)
613 }
614
615 /// `calcFunc-gcd`.
616 static func gcd(_ a: Value, _ b: Value) throws -> Value {
617 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
618 let a = isWhole(a) ? .int(try trunc(a)) : a
619 let b = isWhole(b) ? .int(try trunc(b)) : b
620 if case .int(let x) = a, case .int(let y) = b {
621 guard x != .min, y != .min else { throw Unsupported("integer size") }
622 return .int(gcd(x, y))
623 }
624 if try sign(a) < 0 { return try Calc.gcd(try negate(a), b) }
625 if try sign(b) < 0 { return try Calc.gcd(a, try negate(b)) }
626 guard let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { throw Unsupported("arguments") }
627 guard case .int(let g) = try Calc.gcd(.int(d1), .int(d2)) else { throw Unsupported("arguments") }
628 let (product, overflow) = d1.multipliedReportingOverflow(by: d2 / g)
629 if overflow { throw Unsupported("integer size") }
630 return try fraction(gcd(n1, n2), product)
631 }
632
633 /// `calcFunc-choose` of integers.
634 static func choose(_ n: Int, _ m: Int) throws -> Int {
635 if m >= 0, m <= n {
636 var c = 1
637 var top = n
638 for i in stride(from: 1, through: m > n / 2 ? n - m : m, by: 1) {
639 let (product, overflow) = c.multipliedReportingOverflow(by: top)
640 if overflow { throw Unsupported("integer size") }
641 c = product / i
642 top -= 1
643 }
644 return c
645 }
646 if n < 0, m >= 0 {
647 let v = try choose(m - n - 1, m)
648 return m % 2 == 0 ? v : -v
649 }
650 if n < 0 {
651 if n < m { return 0 }
652 let v = try choose(-m - 1, n - m)
653 return (n - m) % 2 == 0 ? v : -v
654 }
655 return 0
656 }
657
309 // MARK: - Display 658 // MARK: - Display
310 659
311 /// `math-format-number`. 660 /// `math-format-number`.
@@ -488,15 +837,32 @@ public enum Calc {
488 return left 837 return left
489 } 838 }
490 839
840 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`.
491 mutating func product() throws -> Node { 841 mutating func product() throws -> Node {
492 var left = try unary() 842 var left = try unary()
493 while peek() == "*" { 843 while let c = peek() {
494 i += 1 844 if c == "*" {
845 i += 1
846 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
847 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
848 break
849 }
495 left = .binary("*", left, try unary()) 850 left = .binary("*", left, try unary())
496 } 851 }
497 return left 852 return left
498 } 853 }
499 854
855 /// `math-factor-after`: whether what follows can start an operand, which makes `%`
856 /// the modulo operator rather than percent.
857 func factorAfter(_ j: Int) -> Bool {
858 var j = j
859 while j < chars.count, chars[j] == " " || chars[j] == "\t" { j += 1 }
860 guard j < chars.count else { return false }
861 let c = chars[j]
862 if c == ".", j + 1 < chars.count { return chars[j + 1].isASCII && chars[j + 1].isNumber }
863 return (c.isASCII && c.isNumber) || c.isLetter || "$#\"-+!([{".contains(c)
864 }
865
500 mutating func unary() throws -> Node { 866 mutating func unary() throws -> Node {
501 if let c = peek(), c == "-" || c == "+" { 867 if let c = peek(), c == "-" || c == "+" {
502 i += 1 868 i += 1
@@ -507,7 +873,28 @@ public enum Calc {
507 } 873 }
508 874
509 mutating func powerNode() throws -> Node { 875 mutating func powerNode() throws -> Node {
510 let base = try primary() 876 var base = try primary()
877 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
878 while let c = peek() {
879 let next = i + 1 < chars.count ? chars[i + 1] : nil
880 if c == "%", !factorAfter(i + 1) {
881 // `%%` starts a comment.
882 if next == "%" { throw Unsupported("formula syntax") }
883 i += 1
884 base = .call("percent", [base])
885 } else if c == "!", next != "=" {
886 if next == "!" {
887 if i + 2 < chars.count, chars[i + 2] == "!" { throw Unsupported("formula syntax") }
888 i += 2
889 base = .call("dfact", [base])
890 } else {
891 i += 1
892 base = .call("fact", [base])
893 }
894 } else {
895 break
896 }
897 }
511 if peek() == "^" { 898 if peek() == "^" {
512 i += 1 899 i += 1
513 return .binary("^", base, try unary()) 900 return .binary("^", base, try unary())
@@ -571,13 +958,41 @@ public enum Calc {
571 throw Unsupported("formula syntax") 958 throw Unsupported("formula syntax")
572 } 959 }
573 960
574 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`. 961 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
962 /// and `1:2:3`, and integers in a radix, `16#FF`.
575 mutating func number() throws -> Value { 963 mutating func number() throws -> Value {
576 var whole = "" 964 var whole = ""
577 while i < chars.count, chars[i].isASCII, chars[i].isNumber { 965 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
578 whole.append(chars[i]) 966 whole.append(chars[i])
579 i += 1 967 i += 1
580 } 968 }
969 if !whole.isEmpty, i + 1 < chars.count, chars[i] == ":", chars[i + 1].isASCII, chars[i + 1].isNumber {
970 var text = whole
971 while i < chars.count, chars[i] == ":" || (chars[i].isASCII && chars[i].isNumber) {
972 text.append(chars[i])
973 i += 1
974 }
975 let parts = text.split(separator: ":", omittingEmptySubsequences: false).map { Int($0) }
976 guard parts.count <= 3, !parts.contains(nil) else { throw Unsupported("formula syntax") }
977 let n = parts.map { $0! }
978 guard n.last != 0 else { throw Unsupported("formula syntax") }
979 if n.count == 2 { return try fraction(n[0], n[1]) }
980 let (product, o1) = n[0].multipliedReportingOverflow(by: n[2])
981 let (sum, o2) = product.addingReportingOverflow(n[1])
982 if o1 || o2 { throw Unsupported("integer size") }
983 return try fraction(sum, n[2])
984 }
985 if !whole.isEmpty, i < chars.count, chars[i] == "#" {
986 i += 1
987 var text = ""
988 while i < chars.count, chars[i].isASCII, chars[i].isLetter || chars[i].isNumber || chars[i] == "." || chars[i] == ":" || chars[i] == "#" {
989 text.append(chars[i])
990 i += 1
991 }
992 guard let radix = Int(whole), (2...36).contains(radix), !text.isEmpty,
993 let value = Int(text, radix: radix) else { throw Unsupported("formula syntax") }
994 return .int(value)
995 }
581 var fraction: String? 996 var fraction: String?
582 if i < chars.count, chars[i] == "." { 997 if i < chars.count, chars[i] == "." {
583 i += 1 998 i += 1
@@ -630,40 +1045,44 @@ public enum Calc {
630 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1) 1045 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1)
631 case .unary(_, let operand): return try negate(try eval(operand)) 1046 case .unary(_, let operand): return try negate(try eval(operand))
632 case .binary(let op, let l, let r): 1047 case .binary(let op, let l, let r):
633 let a = try eval(l) 1048 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): 1049 case .call(let name, let args):
658 return try call(name, try args.map(eval)) 1050 return try call(name, try args.map(eval))
659 } 1051 }
660 } 1052 }
661 1053
1054 func binary(_ op: Character, _ a: Value, _ b: Value) throws -> Value {
1055 switch op {
1056 case "+": return try add(a, b)
1057 case "-": return try subtract(a, b)
1058 case "*": return try multiply(a, b)
1059 case "/": return try divide(a, b, fractions: modes.preferFractions)
1060 case "%": return try mod(a, b)
1061 case "\\": return try idiv(a, b)
1062 case "^": return try power(a, b, fractions: modes.preferFractions)
1063 // `calcFunc-lor` and `calcFunc-land` give one of their arguments.
1064 case "|": return try truth(a) ? a : b
1065 case "&": return try truth(a) ? b : a
1066 default:
1067 let order = try compare(a, b)
1068 let holds = switch op {
1069 case "=": order == 0
1070 case "≠": order != 0
1071 case "<": order < 0
1072 case ">": order > 0
1073 case "≤": order <= 0
1074 default: order >= 0
1075 }
1076 return .int(holds ? 1 : 0)
1077 }
1078 }
1079
662 /// A condition's value: a number, nonzero for true. 1080 /// A condition's value: a number, nonzero for true.
663 func truth(_ v: Value) throws -> Bool { 1081 func truth(_ v: Value) throws -> Bool {
664 switch v { 1082 switch v {
665 case .int(let i): return i != 0 1083 case .int(let i): return i != 0
666 case .float(let m, _): return m != 0 1084 case .float(let m, _): return m != 0
1085 case .frac: return true
667 default: throw Unsupported("condition") 1086 default: throw Unsupported("condition")
668 } 1087 }
669 } 1088 }
@@ -695,26 +1114,36 @@ public enum Calc {
695 return .int(i) 1114 return .int(i)
696 } 1115 }
697 1116
698 /// The sum of squared deviations from the mean, and the count. 1117 /// `math-covariance` of numbers without error forms: the variance of `xs` without `ys`,
699 func deviations(_ args: [Value]) throws -> (Value, Int) { 1118 /// with `correlation` the correlation coefficient.
700 let items = try elements(args) 1119 func covariance(_ xs: [Value], _ ys: [Value]? = nil, population: Bool, correlation: Bool = false) throws -> Value {
701 guard !items.isEmpty else { throw Unsupported("empty vector") } 1120 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) 1121 guard n > 0 else { throw Unsupported("empty vector") }
703 let squares = try items.reduce(Value.int(0)) { sum, x in 1122 guard population || n > 1 else { throw Unsupported(ys == nil ? "variance of one value" : "arguments") }
704 let d = try subtract(x, mean) 1123 guard (ys ?? xs).count == n else { throw Unsupported("arguments") }
705 return try add(sum, try multiply(d, d)) 1124 return try extra(2) {
1125 func sum(_ v: [Value]) throws -> Value { try v.dropFirst().reduce(v[0], add) }
1126 func deviations(_ v: [Value]) throws -> [Value] {
1127 let shift = try divide(try sum(v), .int(-n), fractions: modes.preferFractions)
1128 return try v.map { try add($0, shift) }
1129 }
1130 let dx = try deviations(xs)
1131 let dy = try ys.map(deviations) ?? dx
1132 let products = try sum(try zip(dx, dy).map(multiply))
1133 let divisor = correlation
1134 ? try squareRoot(try multiply(try sum(try dx.map { try multiply($0, $0) }), try sum(try dy.map { try multiply($0, $0) })))
1135 : .int(population ? n : n - 1)
1136 return try divide(products, divisor, fractions: modes.preferFractions)
706 } 1137 }
707 return (squares, items.count)
708 }
709
710 func root(_ x: Value) throws -> Value {
711 try call("sqrt", [x])
712 } 1138 }
713 1139
1140 /// `math-flatten-many-vecs`: the arguments, vectors flattened into their elements.
714 func elements(_ args: [Value]) throws -> [Value] { 1141 func elements(_ args: [Value]) throws -> [Value] {
715 guard args.count == 1 else { throw Unsupported("arguments") } 1142 var items: [Value] = []
716 if case .vector(let items) = args[0] { return items } 1143 for arg in args {
717 return [args[0]] 1144 if case .vector(let inner) = arg { items += try elements(inner) } else { items.append(arg) }
1145 }
1146 return items
718 } 1147 }
719 1148
720 func one(_ args: [Value]) throws -> Value { 1149 func one(_ args: [Value]) throws -> Value {
@@ -729,15 +1158,15 @@ public enum Calc {
729 func call(_ name: String, _ args: [Value]) throws -> Value { 1158 func call(_ name: String, _ args: [Value]) throws -> Value {
730 switch name { 1159 switch name {
731 case "vsum": 1160 case "vsum":
732 return try elements(args).reduce(Value.int(0)) { try add($0, $1) } 1161 return try extra(2) { try elements(args).reduce(Value.int(0)) { try add($0, $1) } }
733 case "vprod": 1162 case "vprod":
734 return try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } 1163 return try extra(2) { try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } }
735 case "vcount": 1164 case "vcount":
736 return .int(try elements(args).count) 1165 return .int(try elements(args).count)
737 case "vmean": 1166 case "vmean":
738 let items = try elements(args) 1167 let items = try elements(args)
739 guard !items.isEmpty else { throw Unsupported("empty vector") } 1168 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) 1169 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": 1170 case "vmax", "vmin":
742 let items = try elements(args) 1171 let items = try elements(args)
743 guard var best = items.first else { throw Unsupported("empty vector") } 1172 guard var best = items.first else { throw Unsupported("empty vector") }
@@ -756,22 +1185,21 @@ public enum Calc {
756 guard args.count == 3 else { throw Unsupported("arguments") } 1185 guard args.count == 3 else { throw Unsupported("arguments") }
757 return try truth(args[0]) ? args[1] : args[2] 1186 return try truth(args[0]) ? args[1] : args[2]
758 case "vvar", "vpvar", "vsdev", "vpsdev": 1187 case "vvar", "vpvar", "vsdev", "vpsdev":
759 let (squares, n) = try deviations(args) 1188 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
760 let population = name == "vpvar" || name == "vpsdev" 1189 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": 1190 case "mod":
765 guard args.count == 2 else { throw Unsupported("arguments") } 1191 guard args.count == 2 else { throw Unsupported("arguments") }
766 return try mod(args[0], args[1]) 1192 return try mod(args[0], args[1])
767 case "idiv": 1193 case "idiv":
768 guard args.count == 2 else { throw Unsupported("arguments") } 1194 guard args.count == 2 else { throw Unsupported("arguments") }
769 return try idiv(args[0], args[1]) 1195 return try idiv(args[0], args[1])
770 case "fact": 1196 case "fact", "dfact":
771 guard case .int(let n) = try one(args), n >= 0 else { throw Unsupported("arguments") } 1197 // A float with an integer value gives a float, up to 20.
1198 let x = try one(args)
1199 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) 1200 var result = Value.int(1)
773 for k in stride(from: 2, through: n, by: 1) { result = try multiply(result, .int(k)) } 1201 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 1202 return x == .int(n) ? result : try float(result)
775 case "max", "min": 1203 case "max", "min":
776 guard !args.isEmpty else { throw Unsupported("arguments") } 1204 guard !args.isEmpty else { throw Unsupported("arguments") }
777 var best = args[0] 1205 var best = args[0]
@@ -804,20 +1232,7 @@ public enum Calc {
804 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") } 1232 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") }
805 return .int(i) 1233 return .int(i)
806 case "sqrt": 1234 case "sqrt":
807 let x = try one(args) 1235 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": 1236 case "exp":
822 let x = try one(args) 1237 let x = try one(args)
823 if x == .int(0) { return .int(1) } 1238 if x == .int(0) { return .int(1) }
@@ -839,9 +1254,14 @@ public enum Calc {
839 } 1254 }
840 if n == 1 { return .int(k) } 1255 if n == 1 { return .int(k) }
841 } 1256 }
842 let d = try double(x) 1257 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") } 1258 if isZero(x) { throw Unsupported("logarithm domain") }
844 return try fromDouble(Foundation.log10(d)) 1259 return try extra(2) {
1260 guard case .float(let m, let e) = try float(x), m > 0 else { throw Unsupported("logarithm domain") }
1261 if m == 1 { return try float(.int(e)) }
1262 let digits = digits(Int128(m)) - 1
1263 return try add(try divide(try lnRaw2(.float(m, -digits)), try ln10()), try float(.int(e + digits)))
1264 }
845 case "sin", "cos", "tan": 1265 case "sin", "cos", "tan":
846 let x = try one(args) 1266 let x = try one(args)
847 if modes.degrees, case .int(let i) = x, i % 90 == 0 { 1267 if modes.degrees, case .int(let i) = x, i % 90 == 0 {
@@ -871,6 +1291,198 @@ public enum Calc {
871 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") } 1291 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) 1292 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d)
873 return try fromDouble(angle(r)) 1293 return try fromDouble(angle(r))
1294 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor":
1295 guard args.count == 2 else { throw Unsupported("arguments") }
1296 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"]
1297 return try binary(ops[name]!, args[0], args[1])
1298 case "lnot":
1299 return .int(try truth(try one(args)) ? 0 : 1)
1300 case "percent":
1301 let x = try one(args)
1302 _ = try sign(x)
1303 return try divide(x, .int(100))
1304 case "float", "pfloat":
1305 return try float(try one(args))
1306 case "sign":
1307 return .int(try sign(try one(args)))
1308 case "rounde", "roundu":
1309 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1310 let x = args[0]
1311 _ = try sign(x)
1312 guard args.count == 2 else { return try round(x, even: name == "rounde") }
1313 guard isWhole(args[1]), case let places = try trunc(args[1]) else { throw Unsupported("arguments") }
1314 if places <= 0, case .int = x { return x }
1315 let rounded = try round(try scale(x, places, fractions: true), even: name == "rounde")
1316 return try scale(rounded, -places, fractions: modes.preferFractions)
1317 case "frac":
1318 return try toFraction(try one(args))
1319 case "fdiv":
1320 guard args.count == 2 else { throw Unsupported("arguments") }
1321 func parts(_ v: Value) throws -> (Int, Int) {
1322 if isWhole(v) { return (try trunc(v), 1) }
1323 guard case .frac(let n, let d) = v else { throw Unsupported("arguments") }
1324 return (n, d)
1325 }
1326 let (n1, d1) = try parts(args[0])
1327 let (n2, d2) = try parts(args[1])
1328 guard n2 != 0 else { throw Unsupported("division by zero") }
1329 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
1330 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
1331 if o1 || o2 { throw Unsupported("integer size") }
1332 return try fraction(n, d)
1333 case "gcd":
1334 guard args.count == 2 else { throw Unsupported("arguments") }
1335 return try gcd(args[0], args[1])
1336 case "lcm":
1337 guard args.count == 2 else { throw Unsupported("arguments") }
1338 return try divide(try absolute(try multiply(args[0], args[1])), try gcd(args[0], args[1]), fractions: modes.preferFractions)
1339 case "choose", "perm":
1340 guard args.count == 2, case .int(let n) = args[0], case .int(let m) = args[1] else { throw Unsupported("arguments") }
1341 if name == "choose" { return .int(try choose(n, m)) }
1342 guard m >= 0, m <= n else { throw Unsupported("arguments") }
1343 var result = Value.int(1)
1344 for k in stride(from: n - m + 1, through: n, by: 1) { result = try multiply(result, .int(k)) }
1345 return result
1346 case "pow":
1347 guard args.count == 2 else { throw Unsupported("arguments") }
1348 return try power(args[0], args[1], fractions: modes.preferFractions)
1349 case "exp10":
1350 let x = try one(args)
1351 guard case .int(let n) = x else { throw Unsupported("arguments") }
1352 return n == 0 ? .int(1) : try makeFloat(1, n)
1353 case "nroot":
1354 guard args.count == 2, case .int(let n) = args[1], n >= 1 else { throw Unsupported("arguments") }
1355 _ = try sign(args[0])
1356 return n == 1 ? args[0] : try rootPower(args[0], n)
1357 case "hypot":
1358 guard args.count == 2 else { throw Unsupported("arguments") }
1359 let (a, b) = (args[0], args[1])
1360 _ = (try sign(a), try sign(b))
1361 if isZero(a) { return try absolute(b) }
1362 if isZero(b) { return try absolute(a) }
1363 return try extra(1) { try squareRoot(try add(try multiply(a, a), try multiply(b, b))) }
1364 case "log":
1365 guard args.count == 2 else {
1366 guard args.count == 1 else { throw Unsupported("arguments") }
1367 return try call("ln", args)
1368 }
1369 let (x, b) = (args[0], args[1])
1370 _ = (try sign(x), try sign(b))
1371 if b == .int(10) || b == .float(1, 1) { return try call("log10", [x]) }
1372 if isZero(x) || isZero(b) || b == .int(1) || b == .float(1, 0) { throw Unsupported("logarithm domain") }
1373 if x == .int(1) || x == .float(1, 0) {
1374 if case .float = b { return .float(0, 0) }
1375 return .int(0)
1376 }
1377 if rational(x) != nil, rational(b) != nil, try sign(x) > 0, try sign(b) > 0 {
1378 var sign = 1
1379 var (xx, bb) = (x, b)
1380 if try compare(.int(1), x) >= 0 {
1381 sign = -1
1382 xx = try divide(.int(1), x)
1383 }
1384 if try compare(.int(1), b) >= 0 {
1385 sign = -sign
1386 bb = try divide(.int(1), b)
1387 }
1388 let inverse = try compare(xx, bb) < 0
1389 let (exact, n) = inverse ? try integerLog(bb, xx) : try integerLog(xx, bb)
1390 if exact { return inverse ? try divide(.int(1), .int(sign * n), fractions: modes.preferFractions) : .int(sign * n) }
1391 }
1392 return try extra(2) { try divide(try lnRaw(try float(x)), try lnRaw(try float(b))) }
1393 case "sinh", "cosh":
1394 let x = try one(args)
1395 if x == .int(0) { return .int(name == "sinh" ? 0 : 1) }
1396 _ = try sign(x)
1397 return try extra(2) {
1398 let e = try expRaw(try float(x))
1399 return try multiply(try add(e, try divide(.int(name == "sinh" ? -1 : 1), e)), .float(5, -1))
1400 }
1401 case "tanh":
1402 let x = try one(args)
1403 if x == .int(0) { return x }
1404 _ = try sign(x)
1405 return try extra(2) {
1406 let e = try extra(2) { try expRaw(try float(x)) }
1407 let inverse = try divide(.int(1), e)
1408 return try divide(try subtract(e, inverse), try add(e, inverse))
1409 }
1410 case "arcsinh":
1411 let x = try one(args)
1412 if x == .int(0) { return x }
1413 _ = try sign(x)
1414 return try extra(2) { try lnRaw(try add(x, try squareRootRaw(try add(try multiply(x, x), .float(1, 0))))) }
1415 case "arccosh":
1416 let x = try one(args)
1417 if x == .int(1) { return .int(0) }
1418 guard try compare(x, .int(-1)) != 0 else { throw Unsupported("complex result") }
1419 return try extra(2) {
1420 let xp1 = try add(.int(1), x)
1421 return try lnRaw(try add(x, try multiply(xp1, try squareRootRaw(try divide(try subtract(x, .float(1, 0)), xp1)))))
1422 }
1423 case "arctanh":
1424 let x = try one(args)
1425 if x == .int(0) { return x }
1426 guard try compare(x, .int(1)) <= 0 else { throw Unsupported("complex result") }
1427 return try extra(2) {
1428 try multiply(try lnRaw(try divide(try add(.float(1, 0), x), try subtract(.int(1), x))), .float(5, -1))
1429 }
1430 case "arctan2":
1431 guard args.count == 2 else { throw Unsupported("arguments") }
1432 _ = (try sign(args[0]), try sign(args[1]))
1433 return try extra(2) {
1434 let (y, x) = (try float(args[0]), try float(args[1]))
1435 let r: Value
1436 if isZero(y) {
1437 r = try sign(x) < 0 ? try pi() : .float(0, 0)
1438 } else if isZero(x) {
1439 r = try sign(y) > 0 ? try piOver2() : try negate(try piOver2())
1440 } else if try sign(x) > 0 {
1441 r = try arctanRaw(try divide(y, x))
1442 } else if try sign(y) > 0 {
1443 r = try add(try arctanRaw(try divide(y, x)), try pi())
1444 } else {
1445 r = try subtract(try arctanRaw(try divide(y, x)), try pi())
1446 }
1447 return modes.degrees ? try divide(r, try piOver180()) : r
1448 }
1449 case "deg", "rad":
1450 let x = try one(args)
1451 _ = try sign(x)
1452 return try extra(2) { name == "deg" ? try divide(x, try piOver180()) : try multiply(x, try piOver180()) }
1453 case "vflat":
1454 return .vector(try elements(args))
1455 case "vgmean", "vhmean":
1456 let items = try elements(args)
1457 guard !items.isEmpty else { throw Unsupported("empty vector") }
1458 return try extra(2) {
1459 if name == "vhmean" {
1460 let inverses = try items.map { try divide(.int(1), $0, fractions: modes.preferFractions) }
1461 return try divide(.int(items.count), try inverses.dropFirst().reduce(inverses[0], add), fractions: modes.preferFractions)
1462 }
1463 let product = try items.dropFirst().reduce(items[0], multiply)
1464 return items.count == 2 ? try squareRoot(product) : try rootPower(product, items.count)
1465 }
1466 case "vcov", "vpcov", "vcorr":
1467 // Two vectors; one matrix argument isn't supported.
1468 guard args.count == 2 else { throw Unsupported("arguments") }
1469 return try covariance(try elements([args[0]]), try elements([args[1]]), population: name == "vpcov", correlation: name == "vcorr")
1470 case "agmean":
1471 guard args.count == 2 else { throw Unsupported("arguments") }
1472 let (a, b) = (args[0], args[1])
1473 _ = (try sign(a), try sign(b))
1474 if try compare(a, b) == 0 || isZero(a) { return a }
1475 if isZero(b) { return b }
1476 return try extra(2) {
1477 var (x, y) = (try float(try absolute(a)), try float(try absolute(b)))
1478 for _ in 0..<1000 {
1479 if nearlyEqual(x, y) { return x }
1480 let mean = try multiply(try add(x, y), .float(5, -1))
1481 y = try extra(1) { try squareRootRaw(try multiply(x, y)) }
1482 x = mean
1483 }
1484 throw Unsupported("number")
1485 }
874 default: 1486 default:
875 throw Unsupported("function \(name)") 1487 throw Unsupported("function \(name)")
876 } 1488 }
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 +152 −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,71 @@ 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)", "exp10(2)", "exp10(-2)", "exp10(0)", "exp10(15)",
106 "nroot(8,3)", "nroot(27,3)", "nroot(10,3)", "nroot(16,4)", "nroot(2.5,2)", "nroot(1:8,3)", "nroot(-8,1)",
107 "nroot(2,4)", "nroot(2,5)", "nroot(100,7)", "nroot(1000,12)", "nroot(3.5,11)", "nroot(2:3,3)", "nroot(0,3)",
108 "nroot(1,5)", "nroot(1024,10)", "nroot(7,6)", "nroot(1e10,9)",
109 "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)",
110 "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)",
111 "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)",
112 "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)",
113 "log10(7.5e-8)", "log10(99)", "log10(2:3)",
114 // Hyperbolic and angle functions.
115 "sinh(1)", "sinh(0)", "sinh(-2.5)", "sinh(0.)", "sinh(1:2)", "cosh(1)", "cosh(0)", "cosh(-0.5)", "tanh(1)",
116 "tanh(0)", "tanh(-3)", "tanh(0.25)", "arcsinh(1)", "arcsinh(0)", "arcsinh(-2.5)", "arcsinh(1:2)",
117 "arccosh(2)", "arccosh(1)", "arccosh(1.)", "arccosh(10.5)", "arctanh(0.5)", "arctanh(0)", "arctanh(-0.25)",
118 "arctanh(1:3)", "arctan2(1,1)", "arctan2(1,0)", "arctan2(0,-1)", "arctan2(-1,-1)", "arctan2(0,0)",
119 "arctan2(1,2)", "arctan2(0,1)", "arctan2(-1,0)", "arctan2(3,-4)", "arctan2(-2.5,1)",
120 "deg(1)", "deg(3.14159)", "deg(1:2)", "rad(180)", "rad(90)", "rad(1)", "rad(-45.5)",
121 "float(7)", "float(7:2)", "float(2.5)", "pfloat(7)", "float(1:3)", "float(123456789012345)",
122 "sqrt(2)", "sqrt(1e6)", "sqrt(10)", "sqrt(2:9)", "sqrt(0.5)", "sqrt(99999999)",
123 ]
124
125 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
126 /// cases `Calc.evaluate` doesn't support.
127 static func compare(_ cases: [(String, String)], precision: Int = 12) throws -> [String] {
128 let emacs = try CalcOracle.run(cases, precision: precision)
85 #expect(emacs.count == cases.count) 129 #expect(emacs.count == cases.count)
86 var skipped: [String] = [] 130 var skipped: [String] = []
87 for (c, expected) in zip(cases, emacs) { 131 for (c, expected) in zip(cases, emacs) {
88 var modes = Calc.Modes() 132 var modes = Calc.Modes()
133 modes.precision = precision
89 let f = c.1.dropFirst().dropLast().split(separator: " ") 134 let f = c.1.dropFirst().dropLast().split(separator: " ")
90 let n = Int(f[1])! 135 let n = Int(f[1])!
91 switch f[0] { 136 switch f[0] {
@@ -100,15 +145,99 @@ struct CalcTests {
100 skipped.append(c.0) 145 skipped.append(c.0)
101 continue 146 continue
102 } 147 }
103 #expect(ours == expected, "\(c.0) \(c.1)") 148 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)")
149 }
150 return skipped
151 }
152
153 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
154 func matchesCalc() throws {
155 var cases = Self.fixed.map { ($0, "(float 8)") }
156 for format in ["(float 3)", "(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
157 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) }
158 }
159 // Generated: random operands and operators.
160 var generator = SystemRandomNumberGenerator()
161 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"]
162 let ops = ["+", "-", "*", "/"]
163 for _ in 0..<300 {
164 var e = numbers.randomElement(using: &generator)!
165 for _ in 0..<Int.random(in: 1...4, using: &generator) {
166 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
167 }
168 cases.append((e, "(float 8)"))
104 } 169 }
105 // Only what Calc itself can't show as a number. 170 // Only what Calc itself can't show as a number.
171 let skipped = try Self.compare(cases)
106 #expect(skipped == [], "\(skipped)") 172 #expect(skipped == [], "\(skipped)")
107 } 173 }
108 174
175 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
176 func functionsMatchCalc() throws {
177 var cases = Self.functions.map { ($0, "(float 12)") }
178 let sample = ["vgmean([1,2,3])", "agmean(1,2)", "sinh(1)", "arctan2(1,2)", "frac(0.1)", "log(10,2)", "nroot(10,3)",
179 "vcorr([1,2,3],[1,2,4])", "5%", "1:3*3", "rounde(2.45,1)", "hypot(1,1)", "rad(1)", "16#FF/7"]
180 for format in ["(float 8)", "(fix 2)", "(sci 3)", "(eng 2)"] {
181 for e in sample { cases.append((e, format)) }
182 }
183 // Generated: functions of random integers, fractions and floats. Arguments outside a
184 // function's domain are refused, so only what is computed is compared.
185 var generator = SystemRandomNumberGenerator()
186 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"]
187 let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
188 let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
189 for _ in 0..<200 {
190 let x = numbers.randomElement(using: &generator)!
191 let y = numbers.randomElement(using: &generator)!
192 cases.append(("\(unary.randomElement(using: &generator)!)(\(x))", "(float 12)"))
193 cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
194 cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
195 }
196 let skipped = Set(try Self.compare(cases)).intersection(Self.functions + sample)
197 #expect(skipped == [], "\(skipped)")
198 }
199
200 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
201 func precisionMatchesCalc() throws {
202 var generator = SystemRandomNumberGenerator()
203 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",
204 "1.23456789012345678", "123456789.987654321"]
205 let ops = ["+", "-", "*", "/"]
206 for precision in [3, 6, 15, 18] {
207 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",
208 "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
209 // Two digits more must fit in 18.
210 if precision <= 16 {
211 cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])"].map { ($0, "(float 0)") }
212 }
213 if precision <= 14 {
214 cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5"].map { ($0, "(float 0)") }
215 }
216 for _ in 0..<100 {
217 var e = numbers.randomElement(using: &generator)!
218 for _ in 0..<Int.random(in: 1...3, using: &generator) {
219 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
220 }
221 cases.append((e, "(float 0)"))
222 }
223 let skipped = try Self.compare(cases, precision: precision)
224 #expect(skipped == [], "p\(precision) \(skipped)")
225 }
226 }
227
109 @Test func unsupported() { 228 @Test func unsupported() {
110 for e in ["abc*2", "1/0", "vmean([])", "pi", "5%", "(-8)^(1/3)", "2 3", "vvar([5])", "1<2<3"] { 229 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3",
230 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
231 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
232 "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",
233 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
234 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)"] {
111 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) } 235 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
112 } 236 }
237 var modes = Calc.Modes()
238 modes.precision = 15
239 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
240 modes.precision = 19
241 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
113 } 242 }
114} 243}
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 +42 −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.
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,8 @@ 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, precisions beyond those given under
519 =S= and =u= flags; 546 /Mode flags and formats/, and the =S= and =u= flags;
520- division by zero, complex results, vector results, and numbers too large for 547- division by zero, complex results, vector results, and numbers too large for
521 64-bit integers; 548 64-bit integers;
522- Lisp functions not listed above. 549- Lisp functions not listed above.