Passing Equations in Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bwv2
Forum Commoner
Posts: 83
Joined: Fri Jun 10, 2005 11:50 am
Location: AZ

Passing Equations in Variables

Post by bwv2 »

I'm trying to figure something out and can't quite get it. Here's background on what I'm doing:

A process can be solved by using a mathematical equation (simple polynomial of degree <=4). Different equations are to be used depending on the circumstances of the situation. The different equations that can be used for each circumstance are stored as VARCHAR entries in a mySQL table.

Here's what I want to do:

1. pull equation out of mySQL and store it in a variable (as a string?)
2. The equation is a function of one variable: "x", so assign some variable in my script to be $x="x"
3. Solve the equation and get an output variable.

Here is how I would think to do it (probably incorrectly), see if you have a better idea:

Code: Select all

//query the equation
$sql="SELECT equation FROM table WHERE id=3";
$result=mysql_query($sql) or die(mysql_error());
$equation=mysql_fetch_result($result,0,0);  

//the equation now stored in $equation is this: "21 + pow(123*$x,2) + pow(1234*$x,3) "

//assign a value to $x
$x=2;

//form an equation, which I want to give me an outcome
$outcome = $equation;

//print the result of the calculation
print"Result = $outcome";

//should print:  "Result = 10385"
Now I know this is wrong, but does anyone know a way of doing it so that it works? Any help would be greatly appreciated. I think something like this can be done in MATLAB using syms (symbolic math toolbox).
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

may want to look at eval() (dangerous, due to it running as if it were php code)

There are math parsers:

http://pear.php.net/package/Math_RPN/do ... N_php.html
Post Reply