1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Decimal-specific symbol table implementation.
//!
//! This module provides high-precision 128-bit Decimal arithmetic with checked operations.
use super::{FuncError, Symbol};
use crate::number::Number;
use crate::symtable::SymTable;
use rust_decimal::Decimal;
use rust_decimal::prelude::*;
use rust_decimal_macros::dec;
use std::panic;
// Mathematical constants for symbol table
const LN_2: Number = dec!(0.6931471805599453094172321);
const LN_10: Number = dec!(2.3025850929940456840179915);
const SQRT_2: Number = dec!(1.4142135623730950488016887);
/// Helper function for single-argument f64 calculations
/// Used for inverse trig functions that don't have native Decimal implementations
fn f64_calc_1<F>(args: &[Number], func: F) -> Result<Number, FuncError>
where
F: Fn(f64) -> f64,
{
let arg = args[0].to_f64().ok_or(FuncError::ToF64Conversion)?;
let result = func(arg);
Decimal::from_f64(result).ok_or(FuncError::FromF64Conversion)
}
/// Helper function for two-argument f64 calculations
fn f64_calc_2<F>(args: &[Number], func: F) -> Result<Number, FuncError>
where
F: Fn(f64, f64) -> f64,
{
let arg1 = args[0].to_f64().ok_or(FuncError::ToF64Conversion)?;
let arg2 = args[1].to_f64().ok_or(FuncError::ToF64Conversion)?;
let result = func(arg1, arg2);
Decimal::from_f64(result).ok_or(FuncError::FromF64Conversion)
}
/// Cube root using Newton-Raphson iteration
fn cbrt_decimal(x: Decimal) -> Decimal {
if x == Decimal::ZERO {
return Decimal::ZERO;
}
let sign = if x < Decimal::ZERO {
Decimal::NEGATIVE_ONE
} else {
Decimal::ONE
};
let abs_x = x.abs();
// Initial guess using x^(1/3) ≈ x / 3 for small values, or a fraction of x for large
let mut guess = if abs_x < Decimal::ONE {
abs_x
} else {
abs_x / Decimal::from(3)
};
let three = Decimal::from(3);
let precision = Decimal::new(1, 28); // 10^-28
// Newton-Raphson: x_n+1 = (2*x_n + a/x_n²) / 3
for _ in 0..50 {
let guess_squared = guess * guess;
let next = (guess + guess + abs_x / guess_squared) / three;
if (next - guess).abs() < precision {
return next * sign;
}
guess = next;
}
guess * sign
}
#[cfg(feature = "decimal-precision")]
impl SymTable {
/// Creates a symbol table with the standard library for Decimal precision.
///
/// Most functions use native 128-bit `Decimal` arithmetic for high precision.
/// Some operations use f64 conversion internally due to `rust_decimal` limitations:
/// - Inverse trig functions: `asin`, `acos`, `atan`, `atan2`
/// - Power function: `pow` (for non-integer exponents)
///
/// ## Fixed arity functions
/// - `sin(x)` - Sine
/// - `cos(x)` - Cosine
/// - `tan(x)` - Tangent
/// - `asin(x)` - Arcsine
/// - `acos(x)` - Arccosine
/// - `atan(x)` - Arctangent
/// - `atan2(y, x)` - Two-argument arctangent
/// - `sinh(x)` - Hyperbolic sine
/// - `cosh(x)` - Hyperbolic cosine
/// - `tanh(x)` - Hyperbolic tangent
/// - `sqrt(x)` - Square root
/// - `cbrt(x)` - Cube root
/// - `pow(x, y)` - x raised to power y
/// - `log(x)` - Natural logarithm
/// - `log2(x)` - Base-2 logarithm
/// - `log10(x)` - Base-10 logarithm
/// - `exp(x)` - e raised to power x
/// - `exp2(x)` - 2 raised to power x
/// - `abs(x)` - Absolute value
/// - `sign(x)` - Sign function (-1, 0, or 1)
/// - `floor(x)` - Floor function
/// - `ceil(x)` - Ceiling function
/// - `round(x)` - Round to nearest integer
/// - `trunc(x)` - Truncate to integer
/// - `fract(x)` - Fractional part
/// - `mod(x, y)` - Remainder of x/y
/// - `hypot(x, y)` - Euclidean distance sqrt(x²+y²)
/// - `clamp(x, min, max)` - Constrain value between bounds
///
/// ## Variadic functions
/// - `min(x, ...)` - Minimum value
/// - `max(x, ...)` - Maximum value
/// - `sum(x, ...)` - Sum of values
/// - `avg(x, ...)` - Average of values
pub fn stdlib() -> Self {
Self::from_symbols(vec![
// Constants
Symbol::Const {
name: "pi".into(),
value: Decimal::PI,
description: Some("π (3.14159...)".into()),
local: false,
},
Symbol::Const {
name: "e".into(),
value: Decimal::E,
description: Some("Euler's number (2.71828...)".into()),
local: false,
},
Symbol::Const {
name: "tau".into(),
value: Decimal::TWO_PI,
description: Some("2π (6.28318...)".into()),
local: false,
},
Symbol::Const {
name: "ln2".into(),
value: LN_2,
description: Some("Natural logarithm of 2".into()),
local: false,
},
Symbol::Const {
name: "ln10".into(),
value: LN_10,
description: Some("Natural logarithm of 10".into()),
local: false,
},
Symbol::Const {
name: "sqrt2".into(),
value: SQRT_2,
description: Some("Square root of 2".into()),
local: false,
},
// Trigonometric functions
Symbol::Func {
name: "sin".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].sin()),
description: Some("Sine".into()),
local: false,
},
Symbol::Func {
name: "cos".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].cos()),
description: Some("Cosine".into()),
local: false,
},
Symbol::Func {
name: "tan".into(),
args: 1,
variadic: false,
callback: |args| {
let input = args[0];
match panic::catch_unwind(panic::AssertUnwindSafe(|| input.tan())) {
Ok(result) => Ok(result),
Err(_) => Err(FuncError::DomainError {
function: "tan".to_string(),
input,
}),
}
},
description: Some("Tangent".into()),
local: false,
},
Symbol::Func {
name: "asin".into(),
args: 1,
variadic: false,
callback: |args| f64_calc_1(args, |x| x.asin()),
description: Some("Arcsine".into()),
local: false,
},
Symbol::Func {
name: "acos".into(),
args: 1,
variadic: false,
callback: |args| f64_calc_1(args, |x| x.acos()),
description: Some("Arccosine".into()),
local: false,
},
Symbol::Func {
name: "atan".into(),
args: 1,
variadic: false,
callback: |args| f64_calc_1(args, |x| x.atan()),
description: Some("Arctangent".into()),
local: false,
},
Symbol::Func {
name: "atan2".into(),
args: 2,
variadic: false,
callback: |args| f64_calc_2(args, |y, x| y.atan2(x)),
description: Some("Two-argument arctangent".into()),
local: false,
},
Symbol::Func {
name: "sinh".into(),
args: 1,
variadic: false,
callback: |args| {
let x = args[0];
// sinh(x) = (e^x - e^-x) / 2
match (
panic::catch_unwind(panic::AssertUnwindSafe(|| x.exp())),
panic::catch_unwind(panic::AssertUnwindSafe(|| (-x).exp())),
) {
(Ok(exp_x), Ok(exp_neg_x)) => Ok((exp_x - exp_neg_x) / Decimal::TWO),
_ => Err(FuncError::MathError {
message: "Exponential overflow or underflow in sinh".to_string(),
}),
}
},
description: Some("Hyperbolic sine".into()),
local: false,
},
Symbol::Func {
name: "cosh".into(),
args: 1,
variadic: false,
callback: |args| {
let x = args[0];
// cosh(x) = (e^x + e^-x) / 2
match (
panic::catch_unwind(panic::AssertUnwindSafe(|| x.exp())),
panic::catch_unwind(panic::AssertUnwindSafe(|| (-x).exp())),
) {
(Ok(exp_x), Ok(exp_neg_x)) => Ok((exp_x + exp_neg_x) / Decimal::TWO),
_ => Err(FuncError::MathError {
message: "Exponential overflow or underflow in cosh".to_string(),
}),
}
},
description: Some("Hyperbolic cosine".into()),
local: false,
},
Symbol::Func {
name: "tanh".into(),
args: 1,
variadic: false,
callback: |args| {
let x = args[0];
// tanh(x) = sinh(x) / cosh(x) = (e^x - e^-x) / (e^x + e^-x)
match (
panic::catch_unwind(panic::AssertUnwindSafe(|| x.exp())),
panic::catch_unwind(panic::AssertUnwindSafe(|| (-x).exp())),
) {
(Ok(exp_x), Ok(exp_neg_x)) => {
let sinh_x = exp_x - exp_neg_x;
let cosh_x = exp_x + exp_neg_x;
Ok(sinh_x / cosh_x)
}
_ => Err(FuncError::MathError {
message: "Exponential overflow or underflow in tanh".to_string(),
}),
}
},
description: Some("Hyperbolic tangent".into()),
local: false,
},
// Power and root functions
Symbol::Func {
name: "sqrt".into(),
args: 1,
variadic: false,
callback: |args| {
args[0]
.sqrt()
.ok_or_else(|| FuncError::NegativeSqrt { value: args[0] })
},
description: Some("Square root".into()),
local: false,
},
Symbol::Func {
name: "cbrt".into(),
args: 1,
variadic: false,
callback: |args| Ok(cbrt_decimal(args[0])),
description: Some("Cube root".into()),
local: false,
},
Symbol::Func {
name: "pow".into(),
args: 2,
variadic: false,
callback: |args| {
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
let base = args[0];
let exponent = args[1];
// Convert to f64, compute power, convert back
let base_f64 = base.to_f64().ok_or(FuncError::ToF64Conversion)?;
let exp_f64 = exponent.to_f64().ok_or(FuncError::ToF64Conversion)?;
let result_f64 = base_f64.powf(exp_f64);
Decimal::from_f64(result_f64).ok_or(FuncError::FromF64Conversion)
},
description: Some("x raised to power y".into()),
local: false,
},
// Logarithmic and exponential functions
Symbol::Func {
name: "log".into(),
args: 1,
variadic: false,
callback: |args| {
if args[0] <= Decimal::ZERO {
Err(FuncError::DomainError {
function: "log".to_string(),
input: args[0],
})
} else {
Ok(args[0].ln())
}
},
description: Some("Natural logarithm".into()),
local: false,
},
Symbol::Func {
name: "log2".into(),
args: 1,
variadic: false,
callback: |args| {
if args[0] <= Decimal::ZERO {
Err(FuncError::DomainError {
function: "log2".to_string(),
input: args[0],
})
} else {
// log2(x) = ln(x) / ln(2)
Ok(args[0].ln() / Decimal::TWO.ln())
}
},
description: Some("Base-2 logarithm".into()),
local: false,
},
Symbol::Func {
name: "log10".into(),
args: 1,
variadic: false,
callback: |args| {
if args[0] <= Decimal::ZERO {
Err(FuncError::DomainError {
function: "log10".to_string(),
input: args[0],
})
} else {
// log10(x) = ln(x) / ln(10)
Ok(args[0].ln() / LN_10)
}
},
description: Some("Base-10 logarithm".into()),
local: false,
},
Symbol::Func {
name: "exp".into(),
args: 1,
variadic: false,
callback: |args| {
let input = args[0];
match panic::catch_unwind(panic::AssertUnwindSafe(|| input.exp())) {
Ok(result) => Ok(result),
Err(_) => Err(FuncError::MathError {
message: "Exponential overflow or underflow".to_string(),
}),
}
},
description: Some("e raised to power x".into()),
local: false,
},
Symbol::Func {
name: "exp2".into(),
args: 1,
variadic: false,
callback: |args| {
let input = args[0];
// exp2(x) = exp(x * ln(2))
let exponent = input * Decimal::TWO.ln();
match panic::catch_unwind(panic::AssertUnwindSafe(|| exponent.exp())) {
Ok(result) => Ok(result),
Err(_) => Err(FuncError::MathError {
message: "Exponential overflow or underflow".to_string(),
}),
}
},
description: Some("2 raised to power x".into()),
local: false,
},
// Basic math functions
Symbol::Func {
name: "abs".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].abs()),
description: Some("Absolute value".into()),
local: false,
},
Symbol::Func {
name: "sign".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].signum()),
description: Some("Sign function (-1, 0, or 1)".into()),
local: false,
},
Symbol::Func {
name: "floor".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].floor()),
description: Some("Floor function".into()),
local: false,
},
Symbol::Func {
name: "ceil".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].ceil()),
description: Some("Ceiling function".into()),
local: false,
},
Symbol::Func {
name: "round".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].round()),
description: Some("Round to nearest integer".into()),
local: false,
},
Symbol::Func {
name: "trunc".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].trunc()),
description: Some("Truncate to integer".into()),
local: false,
},
Symbol::Func {
name: "fract".into(),
args: 1,
variadic: false,
callback: |args| Ok(args[0].fract()),
description: Some("Fractional part".into()),
local: false,
},
Symbol::Func {
name: "mod".into(),
args: 2,
variadic: false,
callback: |args| Ok(args[0] % args[1]),
description: Some("Remainder of x/y".into()),
local: false,
},
Symbol::Func {
name: "hypot".into(),
args: 2,
variadic: false,
callback: |args| {
let x = args[0];
let y = args[1];
// hypot(x, y) = sqrt(x² + y²)
let sum_of_squares = x * x + y * y;
sum_of_squares.sqrt().ok_or_else(|| FuncError::MathError {
message: "hypot: sqrt failed (should not happen for sum of squares)"
.to_string(),
})
},
description: Some("Euclidean distance sqrt(x²+y²)".into()),
local: false,
},
Symbol::Func {
name: "clamp".into(),
args: 3,
variadic: false,
callback: |args| Ok(args[0].clamp(args[1].min(args[2]), args[2].max(args[1]))),
description: Some("Constrain value between bounds".into()),
local: false,
},
// Variadic functions
Symbol::Func {
name: "min".into(),
args: 1,
variadic: true,
callback: |args| {
Ok(*args.iter().min().ok_or_else(|| FuncError::MathError {
message: "min() requires at least one argument".to_string(),
})?)
},
description: Some("Minimum value".into()),
local: false,
},
Symbol::Func {
name: "max".into(),
args: 1,
variadic: true,
callback: |args| {
Ok(*args.iter().max().ok_or_else(|| FuncError::MathError {
message: "max() requires at least one argument".to_string(),
})?)
},
description: Some("Maximum value".into()),
local: false,
},
Symbol::Func {
name: "sum".into(),
args: 1,
variadic: true,
callback: |args| Ok(args.iter().sum()),
description: Some("Sum of values".into()),
local: false,
},
Symbol::Func {
name: "avg".into(),
args: 1,
variadic: true,
callback: |args| {
let sum: Decimal = args.iter().sum();
let count = Decimal::from(args.len());
Ok(sum / count)
},
description: Some("Average of values".into()),
local: false,
},
])
}
}