Interpret User-specified Mathematics - c++

I have a program which loops through a number of data points, performs an operation on each data point, and returns a result for each data point. Say,
for(int i=1;i<LEN-1;++i)
result[i]=operate(userfunc,i);
Internally, I can define several variables which contain the values of various neighbours of the data point.
double operate(string userfunc, int i){
double next=data[i+1];
double prev=data[i-1];
double me=data[i];
userfunc(me,prev,next);
}
I imagine the user providing an input string containing the mathematical operation they'd like to perform along with the variables they'd like to work with, such as:
0.5+me*min(prev,next)
My question then is whether there exists a library which would facilitate parsing the user's input. My current thoughts include using Boost.Spirit or a number of regular expressions. But perhaps there is an easier way.

Related

How to use chop with if in Mathematica?

Suppose we have a set of 2 functions with multiple common arguments (x,y,z), let f_i(x,y,z) be one of those functions. When these arguments are evaluated by specific real numbers, Mathematica provides a solution which contains a real part and a very small irreal number (which I think is a calculation error), for the two functions.
I would like to create a new function with the same arguments that, when evaluated, chooses only the real part of the result of the function whose real result satisfies a certain criteria (e.g. be between -1 and 0).
This final function should allow me to plot the real part that matches the criteria in terms of any of its variables and to create other new functions.
I have tried the Chop and If functions in multiple orders without any success. My problem is that the chop function operates directly on the unevaluated functions and thus, does not allow me to attain the mentioned objective.
f[x_, y_, z_] =If[-1 <= Chop[f_1[x, y, z]] <= 0,Chop[f_1[x, y, z]],Chop[f_2[x, y, z]]]
Thank you very much.

Dynamically Allocating an Array from a Polynomial Function String

So I have a polynomial addition problem like the one below:
(1*x+2*x^3-1*x+7)+(1+1*x^2-1*x+1*x^4)
I need to figure out how to extract the numbers for the coefficients and exponents and enter them into a dynamically allocated 2D array (from here I can sort them and add them together before outputting the answer).
I am pretty lost on how to do this because the polynomials can be in any order of degrees and include any amount of terms. I can dynamically allocate them after I extract all of the numbers. The part I need help on is:
Extracting all of the numbers
Differentiating between them to see if it is a coefficient or an exponent
Allowing this to happen for any number of terms
If anyone could answer this or at least point me in the right direction it would be appreciated.
Your problem looks like its parsing and evaluation.
Step1: You need to parse the string assuming an infix expression, so
that you can pull out the coefficient
Step2: push those coefficients into a vector/deque etc to perform the
polynomial calculation.
Here are some good examples:
Evaluating arithmetic expressions from string in C++
What is the best way to evaluate mathematical expressions in C++?
To extract coefficients from a string you need to create a parser. You can use special library like boost.spirit, you can use special tool which builds parsers like Flex, or you can make your own manually using regular expressions or not.
To store coeficients you can use std::vector<int> using indexes as power of x, so for 1*x+2*x^3-1*x+7 your vector would have data:
{ 7, -1, 0, 2 } // 7*x^0 + -1*x^1 + 0*x^2 + 2*x^3
then you do not need to sort them to add coefficients. To store all polynoms you would use std::vector<std::vector<int>> accordingly.

What is the most efficient way to recalculate attributes of a Boost Spirit parse with a different symbol table?

I'm using Boost Spirit to implement functionality in some software that allows the user to enter a mathematical equation that will be repeatedly applied to an input stream. Input stream values are represented as symbols using boost::spirit::qi::symbols which the user can reference in their equation. (e.g. out1 = 3 * in1 + in2)
Parsing and compiling the user's equation is not performance sensitive but calculating its output value is as it forms part of a time-critical pipeline.
The standard way Spirit is used within the documentation is to calculate the output (attribute) of an input as it is parsed. However, as between each calculation only the attribute values of the symbols (out1, in1, etc.) will have changed, it feels like there might be a more efficient way to achieve this, perhaps by caching the abstract syntax tree of the expression and reiterating through it.
What is the most efficient way to recalculate the value of this (fixed) equation given a new set of symbol values?
The standard way Spirit is used is not as limited as you seem to think.
While you can use it to calulate an immediate value on the fly, it is much more usual to build an AST tree in the output attribute, that can be transformed (simplified, optimized) and interpreted (e.g. emitting virtual machine or even assembly instructions).
The compiler tutorials show this in full fledged, but the calculator samples are very close to what you seem to be looking for: http://www.boost.org/doc/libs/1_55_0/libs/spirit/example/qi/compiler_tutorial/
calc1 in example/qi/compiler_tutorial/calc1.cpp
Plain calculator example demonstrating the grammar. The parser is a syntax
checker only and does not do any semantic evaluation.
calc2 in example/qi/compiler_tutorial/calc2.cpp
A Calculator example demonstrating the grammar and semantic actions using
plain functions. The parser prints code suitable for a stack based virtual
machine.
calc3 in example/qi/compiler_tutorial/calc3.cpp
A calculator example demonstrating the grammar and semantic actions using
phoenix to do the actual expression evaluation. The parser is essentially
an "interpreter" that evaluates expressions on the fly.
Here's where it gets interesting for you, since it stops doing the calculations during parsing:
calc4 in example/qi/compiler_tutorial/calc4.cpp
A Calculator example demonstrating generation of AST. The AST, once
created, is traversed,
To print its contents and
To evaluate the result.
calc5 in example/qi/compiler_tutorial/calc5.cpp
Same as Calc4, this time, we'll incorporate debugging support, plus error
handling and reporting.
calc6 in example/qi/compiler_tutorial/calc6.cpp
Yet another calculator example! This time, we will compile to a simple
virtual machine. This is actually one of the very first Spirit example
circa 2000. Now, it's ported to Spirit2.
calc7 in example/qi/compiler_tutorial/calc7/main.cpp
Now we'll introduce variables and assignment. This time, we'll also be
renaming some of the rules -- a strategy for a grander scheme to come ;-)
This version also shows off grammar modularization. Here you will see how
expressions and statements are built as modular grammars.
calc8 in example/qi/compiler_tutorial/calc8/main.cpp
Now we'll introduce boolean expressions and control structures. Is it
obvious now what we are up to? ;-)
I'm sure you'll find lots of inspiration towards the end of the tutorial!
You can build your own tree of calculator objects which mirrors the AST. So for your example out1 = 3 * in1 + in2 the AST is:
*
3
+
in1
in2
So you'd build an object hierarchy like this:
Multiplier(
Constant(3),
Adder(
Variable(&in1),
Variable(&in2)
)
)
With classes something like:
class Result {
virtual double value() = 0;
};
class Multiplier : public Result {
Multiplier(Result* lhs, Result* rhs);
double value() { return _lhs->value() * _rhs->value(); }
}

numbers flex & bison

I'm writing my first flex and bison program which is a simple calculator, and I'd like the calculator to support complex number operations.
But, I cannot manage to insert or even handle any complex numbers in it, since I need the flex to somehow handle both real value and image value of the complex number in the same time and pass it to the bison, and also I dont know how the bison could handle 2 parameters.
This is my flex file:
As you can see, I tried something but this doesnt even compile (with all the complex number procedure). And just for the record, a complex number would look like 1.000+2.111i, 3i, etc.
If you are going to want to perform arithmetic computations on your imaginary numbers you probably want to create a struct say, "img_t" which has two fields, say, real and img and then write functions that have signatures like "img_t img_add(img_t a, img_t b)". Then your bison productions will call these functions for each operator. Your yyunion should have a field img_t img. You could also do these functions inlne in the bison if you wanted. The key point is that you need a struct in your yyunion that holds an imaginary number.
typedef struct {
double real, img;
} img_t;
%yyunion {
:
:
img_t img;
};
:
:
expr_complex: expr_complex '+' expr_complex { $$ = img_add($1, $3); }
:
:
If you see an integer or double alone in the lex, do you want to turn that into an imaginary number? If that's the case, then you can do away with expr_int and expr_double and have all your lex tokens return img_t.
If you post some of the expressions you want to parse and evaluate I can make further comments.

calculating user defined formulas (with c++)

We would like to have user defined formulas in our c++ program.
e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this ? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that ?
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead.
You can represent your formula as a tree of operations and sub-expressions. You may want to define types or constants for Operation types and Variables.
You can then easily enough write a method that recurses through the tree, applying the appropriate operations to whatever values you pass in.
Building your own parser for this should be a straight-forward operation:
) convert the equation from infix to postfix notation (a typical compsci assignment) (I'd use a stack)
) wait to get the values you want
) pop the stack of infix items, dropping the value for the variable in where needed
) display results
Using Spirit (for example) to parse (and the 'semantic actions' it provides to construct an expression tree that you can then manipulate, e.g., evaluate) seems like quite a simple solution. You can find a grammar for arithmetic expressions there for example, if needed... (it's quite simple to come up with your own).
Note: Spirit is very simple to learn, and quite adapted for such tasks.
There's generally two ways of doing it, with three possible implementations:
as you've touched on yourself, a library to evaluate formulas
compiling the formula into code
The second option here is usually done either by compiling something that can be loaded in as a kind of plugin, or it can be compiled into a separate program that is then invoked and produces the necessary output.
For C++ I would guess that a library for evaluation would probably exist somewhere so that's where I would start.
If you want to write your own, search for "formal automata" and/or "finite state machine grammar"
In general what you will do is parse the string, pushing characters on a stack as you go. Then start popping the characters off and perform tasks based on what is popped. It's easier to code if you force equations to reverse-polish notation.
To make your life easier, I think getting this kind of input is best done through a GUI where users are restricted in what they can type in.
If you plan on doing it from the command line (that is the impression I get from your post), then you should probably define a strict set of allowable inputs (e.g. only single letter variables, no whitespace, and only certain mathematical symbols: ()+-*/ etc.).
Then, you will need to:
Read in the input char array
Parse it in order to build up a list of variables and actions
Carry out those actions - in BOMDAS order
With ANTLR you can create a parser/compiler that will interpret the user input, then execute the calculations using the Visitor pattern. A good example is here, but it is in C#. You should be able to adapt it quickly to your needs and remain using C++ as your development platform.