mathexpr, a math expression evaluator library in Nim
This is a mathematic expression evaluator library in pure Nim (with no third-party dependencies).
It supports many mathematical functions, also you provide variables and add custom functions.
See example.nim
for more info.
Installation
To install mathexpr, simply run:
$ nimble install mathexpr
Documentation
Mathexpr has one exported procedure: proc eval(data: string, vars: TableRef[string, float] = nil): float
:
import mathexpr
echo eval("((4 - 2^3 + 1) * -sqrt(3*3+4*4)) / 2") # 7.5
echo eval("+5^+3+1.1 + a", {"a": 5.0}) # 131.1
Also there's an eval
template to simplify passing a table of variables:
import mathexpr
# Eval template:
eval("a + b", {"a": 1.0, "b": 2.0})
# Eval procedure:
import tables
eval("a + b", {"a": 1.0, "b": 2.0}.newTable)
eval
will return NaN
if expression is invalid or cannot be evaluated!
Also Inf
(Infinity) can be returned if result is very big, or if OverflowError happened.
What is supported?
+
, -
, /
, *
, %
, ^
You can use these operators: These functions are implemented:
-
abs(x)
- the absolute value ofx
-
acos(x)
orarccos(x)
- the arccosine (in radians) ofx
-
asin(x)
orarcsin(x)
- the arcsine (in radians) ofx
-
atan(x)
orarctan(x)
orarctg(x)
- the arctangent (in radians) ofx
-
atan2(x, y)
orarctan2(x, y)
- the arctangent of the quotient from providedx
andy
-
ceil(x)
- the smallest integer greater than or equal tox
-
cos(x)
- the cosine ofx
-
cosh(x)
- the hyperbolic cosine ofx
-
exp(x)
- the exponential function ofx
-
sqrt(x)
- the square root ofx
-
fac(x)
- the factorial ofx
-
floor(x)
- the largest integer not greater thanx
-
ln(x)
- the natural log ofx
-
log(x)
orlog10(x)
- the common logarithm (base 10) ofx
-
log2(x)
- the binary logarithm (base 2) ofx
-
max(x, y, z, ...)
- biggest argument from any number of arguments -
min(x, y, z, ...)
- smallest argument from any number of arguments -
ncr(x, y)
orbinom(x, y)
- the the number of ways a sample ofy
elements can be obtained from a larger set ofx
distinguishable objects where order does not matter and repetitions are not allowed -
npr(x, y)
- the number of ways of obtaining an ordered subset ofy
elements from a set ofx
elements -
pow(x, y)
- thex
to they
power -
sin(x)
- the sine ofx
-
sinh(x)
- the hyperbolic sine ofx
-
tan(x)
- the tangent ofx
-
tanh(x)
- the hyperbolic tangent ofx
Constants:
-
pi
- The circle constant (Ludolph's number) -
tau
- The circle constant, equals to2 * pi
-
e
- Euler's number