PIP 5.9.0
Platform-Independent Primitives
Загрузка...
Поиск...
Не найдено
Класс PIEvaluator

Вычислитель выражений с повторно используемыми скомпилированными инструкциями. Подробнее...

#include <pievaluator.h>

Открытые члены

 PIEvaluator ()
 Создает пустой вычислитель.
 ~PIEvaluator ()
 Уничтожает вычислитель.
void * data ()
 Возвращает пользовательские данные, передаваемые в callback-функции.
void setData (void *_data)
 Устанавливает пользовательские данные для callback-функций.
bool check (const PIString &string)
 Проверяет и компилирует выражение.
bool isCorrect () const
 Возвращает true, если последний вызов check() завершился успешно.
int setVariable (const PIString &name, complexd value=complexd(0.))
 Устанавливает именованную переменную и создает ее при необходимости.
void setVariable (int index, complexd value=0.)
 Устанавливает переменную по индексу.
complexd evaluate ()
 Вычисляет последнее успешно скомпилированное выражение.
void clearCustomVariables ()
 Удаляет добавленные пользователем переменные и сохраняет встроенные константы.
int variableIndex (const PIString &name) const
 Возвращает индекс переменной по имени или -1.
const PIStringList & unknownVariables () const
 Возвращает неизвестные переменные, найденные при последнем check().
const PIStringList & usedVariables () const
 Возвращает переменные, использованные в последнем проверенном выражении.
const PIString & expression () const
 Возвращает нормализованную форму последнего проверенного выражения.
const PIString & error () const
 Возвращает последний статус или текст ошибки из check().
const complexd & lastResult () const
 Возвращает последний результат вычисления.
PIByteArray save () const
 Сериализует состояние вычислителя.
void load (PIByteArray ba)
 Восстанавливает состояние вычислителя из сериализованных данных.

Подробное описание

Вычислитель выражений с повторно используемыми скомпилированными инструкциями.

This class provide mathematical evaluations of custom expression.

Вычислитель подготавливает выражение через check(), сохраняет обработанную форму и список инструкций, а затем повторно вычисляет его после обновления переменных. Встроенные константы: i, pi и e.

Synopsis

PIEvaluator developed for stream evaluations of once set expression. Its create internal list of instructions on function \a check() and executes very fast on function \a evaluate(). Once given expression can be evaluated any times with different variable values. Evaluator supports many common mathematic functions described below. Also its automatic puts unnecessarily signs and bracets. Processed expression can be obtains with function expression(). If there is an error in expression you can get it with function error(). Last evaluated result you can get with function lastResult().

Using

First you should set your variables with function setVariable(). Next give your expression with function check() and check for error with functions isCorrect() and error(). If expression is correct you can get processed expression with function expression() and evaluate it with function evaluate(). You can change variable values without rechecking expression.

Functions

PIEvaluator supports arithmetical operations with complex numbers, this is their list in priority order:

  • ^ (power)
  • * (multiply)
  • / (divide)
  • % (residue)
  • + (add)
  • - (subtract)

In addition there are compare and logical operations:

  • == (equal)
  • != (not equal)
  • > (greater)
  • < (smaller)
  • >= (greater or equal)
  • <= (smaller or equal)
  • && (and)
  • || (or)

Compare and logical functions works with real operators part and returns 0 or 1.

Mathematical functions:

  • sin(x) - sine
  • cos(x) - cosine
  • tg(x) - tangent
  • ctg(x) - cotangent
  • arcsin(x) - arcsine
  • arccos(x) - arccosine
  • arctg(x) - arctangent
  • arcctg(x) - arccotangent
  • sh(x) - hyperbolical sine
  • ch(x) - hyperbolical cosine
  • th(x) - hyperbolical tangent
  • cth(x) - hyperbolical cotangent
  • sqr(x) - square
  • sqrt(x) - square root
  • abs(x) - absolute value
  • sign(x) - sign of real part (-1 or 1)
  • exp(x) - exponent
  • pow(x, p) - x in power p
  • ln(x) - natural logarithm
  • lg(x) - decimal logarithm
  • log(x, b) - logarithm of x with base b
  • im(x) - imaginary part of complex number
  • re(x) - real part of complex number
  • arg(x) - argument of complex number
  • len(x) - length of complex number
  • conj(x) - length of complex number
  • rad(x) - convert degrees to radians
  • deg(x) - convert radians to degrees
  • j0(x) - Bessel function first kind order 0
  • j1(x) - Bessel function first kind order 1
  • jn(x, n) - Bessel function first kind order n
  • y0(x) - Bessel function second kind order 0
  • y1(x) - Bessel function second kind order 1
  • yn(x, n) - Bessel function second kind order n
  • random(s, a) - regular random with shift s and amp a
  • randomn(s, a) - normalize random with shift s and amp a
  • min(x0, x1, ...) - minimum of x0, x1, ...
  • max(x0, x1, ...) - maximum of x0, x1, ...
  • clamp(x, a, b) - trim x on range [a, b]
  • step(x, s) - 0 if x < s, else 1
  • mix(x, a, b) - interpolate between a and b linear for x (a * (1 - x) + b * x)
  • round(x) - round

There are some built-in constans:

  • i (imaginary 1)
  • e
  • pi

All trigonometric functions takes angle in radians.

Example

eval.check("2*sin(pi/2)");
piCout << eval.expression() << "=" << eval.evaluate().real();
// 2*sin(pi/2) = 2
eval.check("10x");
piCout << eval.error() << eval.unknownVariables();
// Unknown variables: "x" {"x"}
eval.setVariable("x", complexd(1, 2));
eval.check("10x");
piCout << eval.error() << eval.unknownVariables();
// Correct {}
piCout << eval.expression() << "=" << eval.evaluate();
// 10*x = (10; 20)
eval.setVariable("x", complexd(-2, 0));
piCout << eval.expression() << "=" << eval.evaluate();
// 10*x = (-20; 0)