Programming Environment for Numerical Computing

Math Parser

The parser namespace includes functions to evaluate mathematical expressions:

p = parser.new() New parser. Returns the parser identifier,
    or nil if error
parser.set(p,name,val) Set variable value, where:
p: parser identifier (returned by parser.new)
name: variable name
val: variable value
val = parser.get(p,name) Get variable value, where:
p: parser identifier (returned by parser.new)
name: variable name
Returns variable value
val = parser.eval(p,expr) Evaluate a math expression, where:
p: parser identifier (returned by parser.new)
expr: expression (ex: "x*x + cos(x) - 2")
Returns the expression value
val = parser.evalf(p,expr,x) Evaluate a math expression for a given x value, where:
p: parser identifier (returned by parser.new)
expr: expression (ex: "x*x + cos(x) - 2")
x: x value
Returns the expression value for x
val = parser.solve(p,eq,a,b) Solve nonlinear equation, where:
p: parser identifier (returned by parser.new)
eq: equation to solve (ex: "x*x + cos(x) - 2")
a and b: interval containing a solution
Returns an approximation of the solution x
parser.delete(p) Delete a parser, where:
p: parser identifier (returned by parser.new)

The math parser supports the following functions:

Exp(x) ex
Ln(x) natural (neperian) logarithm
Log(x) decimal logarithm
Log2(x) base-2 logarithm
Sin(x) sine
Cos(x) cosine
Tan(x) tangent
Asin(x) arc sine
Acos(x) arc cosine
Asin(x) arc sine
Atan(x) arc tangent
Sinh(x) hyperbolic sine
Cosh(x) hyperbolic cosine
Tanh(x) hyperbolic tangent
Abs(x) absolute value
Sqrt(x) square root
Cbrt(x) cubic root
Ceil(x) ceiling, the smallest integer not less than x
Floor(x) integer part of x
Rand(x) random number between 0 and 1
Sign(x) sign of x (-1 if x < 0, +1 if x > 0 and 0 if x = 0)
Erf(x) error function
Fact(x) factorial of x

The math parser supports also the following constants:

e Natural (neperian) logarithm base (2.71828...)
Pi 3.14159...
q Electron charge (in C)
me Electron mass (in kg)
mp Proton mass (in kg)
kB Boltzmann constant (J/K)
h Planck constant (Js)
c Speed of Light in vacuum (m/s)
eps0 Electric constant (F/m)
mu0 Magnetic constant (N/A²)
NA Avogadro constant (1/mole)
G Constant of gravitation (m3/kg/s²)
Ri Rydberg constant (1/m)
F Faraday constant (C/m)
R Molar gas constant (J/mole/K)

Example:

Copy the following script in the editor and click Run (or press F12 on Windows and Linux)

-- Parser
cls()

p = parser.new()
parser.set(p, "x", 1)
parser.set(p, "a", 2)
y = parser.eval(p, "a*x + sin(x / a) + 2")
print("y = " .. y)

 

 Copyright(C) 2010-2017 Dr. Sidi HAMADY