C++ Parsing equations provided by the user - c++

I am making a program in C++ that performs some basic calculus functions. In order to create an equation to perform these functions with I am using the following code:
float equationone(float x)
{
return sqrt(x);
}
float equationtwo(float x)
{
return (x * x);
}
I am wondering how can I adapt my code so the user can enter something like sqrt(x) or (x*x) and have the functions return the proper answer.

Not a so trivial task, because you soon would like to have parentheses, operator precedences and so on.
You need to create a parser. If you want to learn how to create one from scratch, try to look for antlr. You basically delegate a tool to create a code that is far from easy to be craft manually. Of course you need to learn how to write a grammar definition, but it probably will pay in the future. If instead you need to serve a real customer in a small time with a scripting language, consider looking on something else than c++.
Have a look at this other reply on Stackoverflow.

You need to write a parser to break up the string into components (numbers, operators etc) then use reverse polish to process it. The page has links on how to convert to infix notation to reverse polish notation. LEX/YACC could help you to do the parsing bit.

Related

How to make input part of my code?

So I have this maths project where I have to write a program which calculates definite integral of a given function within the given boundaries. I've done this using C++ and CodeBlocks, but now I would like to try and make it possible to input function using cmd when I run my code in CodeBlocks, just like I input boundaries, so I don't have to edit this line of code every time I want to run it for different function. I realised that this would require actually using then this input ( e.g. "sqrt(pow(x,2)-1)" ) as part of the code when entered, and I really don't know how to do this or if it is possible at all, so any help is welcome.
This the part of the code which handles function:
double Formula(double x)
{
double a;
a = sqrt(x);
return a;
}
If you want to evaluate expression like "sqrt(pow(x,2)-1)", you have to:
parse the string and generate an AST (Abstract syntax tree) which describes the operations to execute
use an evaluation function on the AST
For example, if you have "sqrt(pow(x,2)-1)" in input, the AST could be represented like this:
function - sqrt
function - substract
function - pow
variable - x
integer - 2
integer - -1
You have to define the structures which will be used to represent your AST.
Then, to parse the query string you have 2 choices:
parse it yourself, count the parentheses etc...
use a tool to generate the parser: yacc + lex or under linux bison + flex. These tools require time to be used to them.
If you have just a little project to do, you may have to try to parse the input yourself to generate the AST.
If the project is a compilation project, you should use bison + flex, they are exactly made for that (but require time to be used to ! ).
Alternatively, integrate with a scripting language, make it do the function parsing and evaluation. It will be considerably slower though.
JavaScript interpreters are all over the place. Python is fairly popular, too. Some people like Lua.

How to parse mathematical formulae from strings in c++

I want to write a program that takes an string like x^2+1 and understand it.
I want to ask the user to enter her/his function and I want to be able to process and understand it. Any Ideas?
char s[100];
s <- "x*I+2"
x=5;
I=2;
res=calc(s);
I think it could be done by something like string analyses but I think Its so hard for me.
I have another Idea and that is using tcc in main program and doing a realtime compile and run and delete a seprated program (or maybe function) that has the string s in it.
and I will create a temp file every time and ask tcc to compile it and run it by exec or similar syntax.
/*tmp.cpp:*/
#include <math.h>
void main(/*input args*/){
return x*I+2;
}
the tmp.cpp will created dynamically.
thanks in advance.
I am not sure what do you expect. It's too complex to give the code as answer, but the general idea is not very complex. It's not out of reach to code, even for a normal hobbyist programmer.
You need to define grammar, tokenize string, recognize operators, constants and variables.
Probably put expression into a tree. Make up a method for substituting the variables... and you can evaluate!
You need to have some kind of a parser. The easiest way to have math operations parsable is to have them written in RPN. You can, however, write your own parser using parser libraries, like Spirit from boost or Yacc
I use with success , function parser
from www it looks like it supports also std::complex, but I never used it
As luck would have it, I recently wrote one!
Look for {,include/}lib/MathExpression/Term. It handles complex numbers but you can easily adapt it for plain old floats.
The licence is GPL 2.
The theory in brief, when you have an expression like
X*(X+2)
Your highest level parser can parse expressions of the form A + B + C... In this case A is the whole expression.
You recurse to parse an operator of higher precedence, A * B * C... In this case A is X and B is (X+2)
Keep recursing until you're parsing either basic tokens such as X or hit an opening parenthesis, in which case push some kind of stack to track where your are and recurse into the parentheses with the top-level low-precedence parser.
I recommend you use RAII and throw exceptions when there are parse errors.
use a Recursive descent parser
Sample: it's in german, but a small and powerfull solution
look here
here is exactly what You are searching for. Change the function read_varname to detect a variable like 'x' or 'I'.

mathematical printf style calculation

I'm looking for an flexible but also considerably fast way to do simple value conversion and calculations at the basis of descriptive calculator strings.
For example something like this:
double r = 1.0;
double d = mathf( "sin(%1)+2*%2", r, M_PI );
double e = mathf( "%1 / 180.0 * %2", r, M_PI );
The important think is the mathematical operations can be evaluated at runtime and loaded from config file. I was even considering some sort of scripting language integration but it seems that doesn't come in sleek and fast?
Any ideas if something like mathf exists for C++?
Try searching around a little more. This is a pretty common thing. It's parsing, and every compiler does it. Makes this a bit like parsception.
Solve equation from string to result in C
Evaluate a simple string mathmatical expression
Convert string to mathematical evaluation
etc etc.
There's two ways to go about it, one is write your own, the second is find a library which seems like what you're looking for. I don't know of anything like that in the C++ standard libs, in ruby and a bunch of other languages for sure, you can just eval the string, but in C++ you're probably going to have to borrow a library from the web or something. Try that last link, it looked promising for that.

Expression Evaluation in C++

I'm writing some excel-like C++ console app for homework.
My app should be able to accept formulas for it's cells, for example it should evaluate something like this:
Sum(tablename\fieldname[recordnumber], fieldname[recordnumber], ...)
tablename\fieldname[recordnumber] points to a cell in another table,
fieldname[recordnumber] points to a cell in current table
or
Sin(fieldname[recordnumber])
or
anotherfieldname[recordnumber]
or
"10" // (simply a number)
something like that.
functions are Sum, Ave, Sin, Cos, Tan, Cot, Mul, Div, Pow, Log (10), Ln, Mod
It's pathetic, I know, but it's my homework :'(
So does anyone know a trick to evaluate something like this?
Ok, nice homework question by the way.
It really depends on how heavy you want this to be. You can create a full expression parser (which is fun but also time consuming).
In order to do that, you need to describe the full grammar and write a frontend (have a look at lex and yacc or flexx and bison.
But as I see your question you can limit yourself to three subcases:
a simple value
a lookup (possibly to an other table)
a function which inputs are lookups
I think a little OO design can helps you out here.
I'm not sure if you have to deal with real time refresh and circular dependency checks. Else they can be tricky too.
For the parsing, I'd look at Recursive descent parsing. Then have a table that maps all possible function names to function pointers:
struct FunctionTableEntry {
string name;
double (*f)(double);
};
You should write a parser. Parser should take the expression i.e., each line and should identify the command and construct the parse tree. This is the first phase. In the second phase you can evaluate the tree by substituting the data for each elements of the command.
Previous responders have hit it on the head: you need to parse the cell contents, and interpret them.
StackOverflow already has a whole slew of questions on building compilers and interperters where you can find pointers to resources. Some of them are:
Learning to write a compiler (#1669 people!)
Learning Resources on Parsers, Interpreters, and Compilers
What are good resources on compilation?
References Needed for Implementing an Interpreter in C/C++
...
and so on.
Aside: I never have the energy to link them all together, or even try to build a comprehensive list.
I guess you cannot use yacc/lex (or the like) so you have to parse "manually":
Iterate over the string and divide it into its parts. What a part is depends on you grammar (syntax). That way you can find the function names and the parameters. The difficulty of this depends on the complexity of your syntax.
Maybe you should read a bit about lexical analysis.

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.