Expand description
§mathexpr
A fast, safe mathematical expression parser and evaluator with bytecode compilation.
§Features
- Fast: Compiles to bytecode for efficient repeated evaluation (~15-80ns per eval)
- Safe: No unsafe code, handles errors gracefully
no_stdcompatible: Works in embedded environments withalloc- Rich function library: 27 built-in functions including trig, rounding, and more
§Quick Start
use mathexpr::Expression;
// Parse and compile an expression
let expr = Expression::parse("sqrt(x^2 + y^2)")?
.compile(&["x", "y"])?;
// Evaluate with different values
assert_eq!(expr.eval(&[3.0, 4.0])?, 5.0);
assert_eq!(expr.eval(&[5.0, 12.0])?, 13.0);§One-liner Evaluation
For simple cases where you don’t need to reuse the expression:
use mathexpr::eval;
let result = eval("2 * pi * r", &["r"], &[5.0])?;§Current Value (_)
Use _ to reference an input value, useful for transformations:
use mathexpr::Expression;
let normalize = Expression::parse("(_ - min) / (max - min)")?
.compile(&["min", "max"])?;
// Normalize 50 to range [0, 100]
let result = normalize.eval_with_current(50.0, &[0.0, 100.0])?;
assert_eq!(result, 0.5);§Supported Operators
| Operator | Description | Precedence |
|---|---|---|
+, - | Addition, Subtraction | Lowest |
*, /, % | Multiplication, Division, Modulo | Medium |
^ | Exponentiation (right-associative) | Highest |
-x | Unary negation | Highest |
§Supported Functions
§Core Math
abs(x),sqrt(x),cbrt(x)- Absolute value, rootslog(x)/ln(x),log2(x),log10(x)- Logarithmsexp(x),pow(base, exp)- Exponentialsmin(a, b),max(a, b),clamp(x, min, max)- Boundsmod(a, b)- Modulo (same as%)
§Trigonometric
sin(x),cos(x),tan(x)- Basic trigasin(x),acos(x),atan(x)- Inverse trigsinh(x),cosh(x),tanh(x)- Hyperbolic
§Rounding
floor(x),ceil(x),round(x),trunc(x)signum(x)- Sign of number
§Constants
piorpi()- π ≈ 3.14159…eore()- Euler’s number ≈ 2.71828…
§Performance
Typical evaluation times (single-threaded, release build):
| Expression Complexity | Time per Eval |
|---|---|
Simple (a + b) | ~15 ns |
Medium (sqrt(x^2 + y^2)) | ~35 ns |
| Complex (5+ functions) | ~70-80 ns |
§Feature Flags
std(default): Enablesstd::error::Errorimplementations- Without
std: Requiresalloccrate, suitable forno_stdenvironments
Re-exports§
pub use ast::BinOp;pub use ast::BuiltinFn;pub use ast::Expr;pub use builder::eval;pub use builder::eval_with_current;pub use builder::Executable;pub use builder::Expression;pub use compiler::CompiledExpr;pub use error::CompileError;pub use error::EvalError;pub use error::ParseError;pub use parser::parse;