math_engine/lib.rs
1//! Tools for parsing and manipulating mathematical expressions
2//!
3//! Math-engine is a set of tools for manipulating mathematical expressions.
4//! These expressions may contain various operations and variables. The crate
5//! defines tools for building, evaluating, and operating on such expressions.
6//!
7//! ## Example
8//!
9//! Math-engine allows you to build variable expressions and evaluate them
10//! within a context, i.e. a set of values for each variable.
11//! ```
12//! let expr = Expression::parse("1.0 + 3.0 * (4.0 - x)").unwrap();
13//! let ctx = Context:new().with_variable("x", 3.0);
14//!
15//! let eval = expr.eval_with_context(&ctx).unwrap();
16//!
17//! assert!(eval, 4.0);
18//! ```
19//!
20//! Basic operators are implemented for allowing easy to use building:
21//! ```
22//! let e1 = Expression::constant(3.0);
23//! let e2 = Expression::variable("x");
24//! let e = e1 + e2;
25//!
26//! println!("{}", e);
27//! ```
28//!
29//! Also, some useful operations are available for manipulating expressions,
30//! such as derivation and simplification by constant propagation:
31//! ```
32//! let e1 = Expression("1.0 * y + 2.0 * x").unwrap();
33//! let deriv = e1.derivate("x");
34//! println!("{}", deriv);
35//!
36//! let simp = deriv.constant_propagation().unwrap();
37//! println!("{}", simp);
38//! ```
39pub mod context;
40pub mod error;
41pub mod expression;
42pub mod parser;
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn parser() {
50 let expr = parser::parse_expression("1.0 + 3.0 * (4.0 - 2.0)").unwrap();
51 let eval = expr.eval().unwrap();
52
53 assert_eq!(eval, 7.0);
54 }
55
56 #[test]
57 fn parser_variable() {
58 let expr = parser::parse_expression("1.0 + x").unwrap();
59 let ctx = context::Context::new().with_variable("x", 4.0);
60 let eval = expr.eval_with_context(&ctx).unwrap();
61
62 assert_eq!(eval, 5.0);
63 }
64}