| @@ -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 | } |