Commit ba8f6b883c

ba8f6b883c469ac81dc19ed2fa282d6736ef696c

parent: 24b578029b

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 17:42 UTC

Calc: exp, ln and powers at two extra digits, exact fraction powers, vmax/vmin at two extra digits, refuse intervals

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +62 −14
@@ -383,12 +383,56 @@ public enum Calc {
383 return try multiply(a, try integerPower(square, n / 2)) 383 return try multiply(a, try integerPower(square, n / 2))
384 } 384 }
385 385
386 /// `math-pow` of real numbers.
386 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value { 387 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
387 if isNaN(a, b) { return .nan } 388 if isNaN(a, b) { return .nan }
388 if case .int(let n) = b { return try integerPower(a, n, fractions: fractions) } 389 _ = (try sign(a), try sign(b))
389 let base = try double(a) 390 var floatB = false
390 guard base >= 0 else { throw Unsupported("complex result") } 391 if case .float = b { floatB = true }
391 return try fromDouble(pow(base, try double(b))) 392 if isZero(a) {
393 // `math-pow-of-zero`.
394 if b == .int(0) { return .int(1) }
395 if isZero(b) { throw Unsupported("arguments") }
396 guard try sign(b) > 0 else { throw Unsupported("division by zero") }
397 return floatB ? try float(a) : a
398 }
399 if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a }
400 if isZero(b) {
401 if case .float = a { return .float(1, 0) }
402 return floatB ? .float(1, 0) : .int(1)
403 }
404 if case .int(let n) = b {
405 if a == .float(1, 1) { return try makeFloat(1, n) }
406 return try extra(2) { try integerPower(a, n, fractions: fractions) }
407 }
408 // `math-pow-fancy`.
409 if let q = quarter(b), (1...3).contains(q) {
410 let root = try squareRoot(floatB ? try float(a) : a)
411 return try power(root, try multiply(.int(2), b), fractions: fractions)
412 }
413 if case .frac(let num, let den) = b, den <= 10, try sign(a) > 0 {
414 return try integerPower(try nthRoot(a, den), num, fractions: fractions)
415 }
416 if a == .int(10) || a == .float(1, 1), isWhole(b) { return try makeFloat(1, try trunc(b)) }
417 guard try sign(a) > 0 else { throw Unsupported("complex result") }
418 return try extra(2) { try expRaw(try float(try multiply(b, try lnRaw(try float(a))))) }
419 }
420
421 /// `math-quarter-integer`: 0 for an integer, 1 to 3 for a number of quarters, else nil.
422 static func quarter(_ x: Value) -> Int? {
423 switch x {
424 case .int: return 0
425 case .frac(let n, let d):
426 if n < 0 { return quarter(.frac(-n, d)).map { 4 - $0 } }
427 return d == 2 ? 2 : d == 4 ? n % 4 : nil
428 case .float(let m, let e):
429 if m < 0 { return quarter(.float(-m, e)).map { 4 - $0 } }
430 if e >= 0 { return 0 }
431 if e == -1 { return m % 10 == 5 ? 2 : nil }
432 if e == -2 { return m % 100 == 25 ? 1 : m % 100 == 75 ? 3 : nil }
433 return nil
434 default: return nil
435 }
392 } 436 }
393 437
394 static func compare(_ a: Value, _ b: Value) throws -> Int { 438 static func compare(_ a: Value, _ b: Value) throws -> Int {
@@ -994,7 +1038,8 @@ public enum Calc {
994 return .int(value) 1038 return .int(value)
995 } 1039 }
996 var fraction: String? 1040 var fraction: String?
997 if i < chars.count, chars[i] == "." { 1041 // `2..5` is an interval, not `2.` then `.5`.
1042 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
998 i += 1 1043 i += 1
999 var f = "" 1044 var f = ""
1000 while i < chars.count, chars[i].isASCII, chars[i].isNumber { 1045 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
@@ -1168,13 +1213,17 @@ public enum Calc {
1168 guard !items.isEmpty else { throw Unsupported("empty vector") } 1213 guard !items.isEmpty else { throw Unsupported("empty vector") }
1169 return try extra(2) { try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) } 1214 return try extra(2) { try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) }
1170 case "vmax", "vmin": 1215 case "vmax", "vmin":
1216 // `math-reduce-many-vecs` compares at two digits more.
1171 let items = try elements(args) 1217 let items = try elements(args)
1172 guard var best = items.first else { throw Unsupported("empty vector") } 1218 guard let first = items.first else { throw Unsupported("empty vector") }
1173 for item in items.dropFirst() { 1219 return try extra(2) {
1174 let order = try compare(item, best) 1220 var best = first
1175 if name == "vmax" ? order > 0 : order < 0 { best = item } 1221 for item in items.dropFirst() {
1222 let order = try compare(item, best)
1223 if name == "vmax" ? order > 0 : order < 0 { best = item }
1224 }
1225 return best
1176 } 1226 }
1177 return best
1178 case "vmedian": 1227 case "vmedian":
1179 var items = try elements(args) 1228 var items = try elements(args)
1180 guard !items.isEmpty else { throw Unsupported("empty vector") } 1229 guard !items.isEmpty else { throw Unsupported("empty vector") }
@@ -1236,13 +1285,12 @@ public enum Calc {
1236 case "exp": 1285 case "exp":
1237 let x = try one(args) 1286 let x = try one(args)
1238 if x == .int(0) { return .int(1) } 1287 if x == .int(0) { return .int(1) }
1239 return try fromDouble(Foundation.exp(try double(x))) 1288 return try extra(2) { try expRaw(try float(x)) }
1240 case "ln": 1289 case "ln":
1241 let x = try one(args) 1290 let x = try one(args)
1242 if x == .int(1) { return .int(0) } 1291 if x == .int(1) { return .int(0) }
1243 let d = try double(x) 1292 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
1244 guard d > 0 else { throw Unsupported("logarithm domain") } 1293 return try extra(2) { try lnRaw(try float(x)) }
1245 return try fromDouble(Foundation.log(d))
1246 case "log10": 1294 case "log10":
1247 let x = try one(args) 1295 let x = try one(args)
1248 if case .int(let i) = x, i > 0 { 1296 if case .int(let i) = x, i > 0 {
Tests/OrgCoreTests/CalcTests.swift +16 −4
@@ -102,7 +102,9 @@ struct CalcTests {
102 "choose(5,2)", "choose(5,0)", "choose(5,6)", "choose(-5,2)", "choose(-5,3)", "choose(-3,-5)", "choose(-5,-3)", 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)", 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. 104 // Powers, roots and logarithms.
105 "pow(2,10)", "pow(2,0.5)", "pow(2,-1)", "exp10(2)", "exp10(-2)", "exp10(0)", "exp10(15)", 105 "pow(2,10)", "pow(2,0.5)", "pow(2,-1)", "8^(1:3)", "pow(8,1:3)", "4^(3:2)", "pow(4,3:2)", "27^(2:3)", "8^(-1:3)",
106 "2^(1:3)", "2^(1:4)", "16^(3:4)", "2^(2:7)", "2^(1:11)", "1.5^(1:3)", "2^1.5", "2^2.5", "2^0.25", "2^-0.5", "2^2.",
107 "3^2.", "10^2.", "10.^3", "10.^-2.", "0^2", "0^2.", "0.^0", "1:4^(1:2)", "(1:8)^(2:3)", "2^1.1", "0.5^0.75", "exp10(2)", "exp10(-2)", "exp10(0)", "exp10(15)",
106 "nroot(8,3)", "nroot(27,3)", "nroot(10,3)", "nroot(16,4)", "nroot(2.5,2)", "nroot(1:8,3)", "nroot(-8,1)", 108 "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)", 109 "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)", 110 "nroot(1,5)", "nroot(1024,10)", "nroot(7,6)", "nroot(1e10,9)",
@@ -208,10 +210,19 @@ struct CalcTests {
208 "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") } 210 "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
209 // Two digits more must fit in 18. 211 // Two digits more must fit in 18.
210 if precision <= 16 { 212 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)") } 213 cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])", "0.7^-3"].map { ($0, "(float 0)") }
212 } 214 }
215 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
216 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
213 if precision <= 14 { 217 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)") } 218 cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5",
219 "exp(1.58)", "ln(9.44)", "0.08^1.5", "0.11^1.5", "exp(8.44)", "pow(2.5,1:3)"].map { ($0, "(float 0)") }
220 // exp, ln and powers round at two digits more first.
221 for _ in 0..<150 {
222 let x = "\(Int.random(in: 1...999, using: &generator))e-2"
223 let y = ["1.5", "0.5", "2.5", "1:3", "0.25", "-1.5", "2.", "3.7", "1.1", "-0.75", "5:7", "1:12"].randomElement(using: &generator)!
224 cases += [("exp(\(x))", "(float 0)"), ("ln(\(x))", "(float 0)"), ("(\(x))^(\(y))", "(float 0)")]
225 }
215 } 226 }
216 for _ in 0..<100 { 227 for _ in 0..<100 {
217 var e = numbers.randomElement(using: &generator)! 228 var e = numbers.randomElement(using: &generator)!
@@ -231,7 +242,8 @@ struct CalcTests {
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)", 242 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
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", 243 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4",
233 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!", 244 "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)"] { 245 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
246 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "0^-1", "0^0.", "ln(0)", "ln(-1)"] {
235 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) } 247 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
236 } 248 }
237 var modes = Calc.Modes() 249 var modes = Calc.Modes()
docs/manual/guide/10-tables.org +4 −3
@@ -397,7 +397,7 @@ After the formula, a =;= starts its flags, as in ~$3=$1/$2;%.2f~ or ~$4=$1*2;f2~
397 397
398Above =p14=, functions worked out from decimal approximations (=sqrt= of a non-square, 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 399=exp=, =ln=, =log=, non-integer powers, trigonometric and hyperbolic functions) may need
400Emacs, and above =p16= so may the statistics functions. 400Emacs, and above =p16= so may the statistics functions and powers of decimal numbers.
401 401
402The 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
403=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
@@ -542,8 +542,9 @@ When a formula uses something the native evaluator doesn't have, the command rep
542what 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:
543 543
544- 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;
545- Calc functions and variables not listed above, precisions beyond those given under 545- Calc functions and variables not listed above, intervals such as =[1..5]=,
546 /Mode flags and formats/, and the =S= and =u= flags; 546 precisions beyond those given under /Mode flags and formats/, and the =S= and =u=
547 flags;
547- division by zero, complex results, vector results, and numbers too large for 548- division by zero, complex results, vector results, and numbers too large for
548 64-bit integers; 549 64-bit integers;
549- Lisp functions not listed above. 550- Lisp functions not listed above.