Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Evaluating user input equations

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
0
0
US
I have a pretty difficult problem. I want the user to be able to enter a function of two variables, then I want to graph the function with Direct3D. Graphing it isn't the problem, it's being able to substitute in for x and y that are the problem. For example, the user enters:

x*y+4*x/y

for f(x,y). How can I plug in values for x and y, then tell the computer to evaluate it? I don't have any idea how to do this, any help would be appreciated.
 
I'm not going to do your coding for you, but you have to interpret the string "x*y+4*x/y". Your compiler does this whenever it parses your source files. If you have a TI-83 calculator, there is similar code in it.

You will need to first write a ‘parser’ to separate the input string into tokens.

Then you will need to write a function that sets up a stack of operations, according to the Order of Operation Precedence and Associativity. This also needs to keep track of where there are algebraic variables in the input string.

The data structure could maybe be something like:

[tt]class Expression;

class Term {
enum TermType { REAL, VARIABLE, EXPRESSION };
union {
double d;
char var_name;
Expression *pSubExpression;
}
};

class Expression {
enum Operand { PLUS='+',
MINUS='-',
TIMES='*',
DIVIDE='/',
POWER='^' };

Term t1, t2;
Operand o;
};[/tt]

Of course you will have to modify this.

Then you need another function which will evaluate the user's function. It will do this by starting at the bottommost Expression, evaluating its t1. If t1's TermType is EXPRESSION, then it evaluates t1.pSubExpression, and so on down the hierarchy. You probably want to use recursive functions to do this.

It will involve a little work.

Will
 
apatterno
I'm not going to do your coding for you

WHAT!! [hammer] I suppose you have something better to do?

[lol]

-pete
[sub]I just can't seem to get back my IntelliSense[/sub]
 
Apatterno,
That's the only way I could figure to do it, but I was hoping there would be an easier way. I wish I could get the people who designed Maple or Mathmatica to give me their code, but I doubt there's much chance of that :(.
 
There are all sorts of parsers, parser generators etc. free on the net. try google for lex and yacc you will get tons of hits. ANTLR is an interesting tool
-pete
[sub]I just can't seem to get back my IntelliSense[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top