Expand description
§formulac
formulac is a Rust library for parsing and evaluating mathematical expressions
with support for complex numbers and extensible user-defined functions.
It allows you to:
- Parse and evaluate expressions containing real and imaginary numbers.
- Use built-in operators, constants, and mathematical functions.
- Register your own variables and functions.
- Work with expressions in a compiled, callable form for repeated evaluation.
Internally, expressions are converted to Reverse Polish Notation (RPN), then compiled into a sequence of stack operations for fast execution.
§Feature Overview
- Complex number support using
num_complex::Complex - Custom functions that can be registered at runtime
- Variables and arguments passed at evaluation time
- Operator precedence and parentheses handling
- Efficient compiled execution avoiding repeated parsing
§Examples
use approx::assert_abs_diff_eq;
use num_complex::Complex;
use formulac::variable::Variables;
use formulac::compile;
// Define available variables
let mut vars = Variables::new();
vars.insert(&[("a", Complex::new(3.0, 4.0))]);
// Compile an expression with arguments
let expr = compile("z + a * 2", &["z"], &vars).unwrap();
// Evaluate the compiled expression with argument a = (1 + 2i)
let result = expr(&[Complex::new(1.0, 2.0)]);
assert_abs_diff_eq!(result.re, 7.0, epsilon = 1.0e-10);
assert_abs_diff_eq!(result.im, 10.0, epsilon = 1.0e-10);§How it works
- The formula string is parsed into tokens.
- Tokens are converted into Reverse Polish Notation (RPN) for unambiguous ordering.
- The RPN sequence is compiled into a closure operating on a stack of
Complex<f64>values. - The resulting closure can be called repeatedly with different arguments for fast evaluation.
Modules§
- variable
- variables.rs
Functions§
- compile
- Compiles a formula string into an executable function.