Jump to content

Recommended Posts

let's say i have a input text that get's a string,something like f=x+2 and i have to calculate for x=2 and return 4.now I want this to work for all kind of inputed functions,not to create every time a function for every combination of variables and functions.I don't know how to explain better but if it's necesary i'll try to do better.this is usually called a php expression evaluator.
hmmm. assuming there's nothing out there and that you had to write it yourself, i dont think (for fairly simple equations) it'd be too hard to write your own. a process along the lines of:
1, using [url=http://www.php.net/preg_replace]preg_replace[/url] to find and replace adjoining number/letter with a * between them (so that, for example, 2x would become 2*x)
2, also using preg_replace to replace the letters with their known values (so that, if x is known and is equal to 4, the equation would be 2*4)
3, using [url=http://www.php.net/eval]eval[/url] to actually execute the calculation from the resulting string

have you tried writing your own as of yet?
it [i]would[/i] definitely work. the problem would come in the case of PHP shifting the equation around (like you'd do if you were solving one for real) depending on where the unknown values are.

so [b]f = x+2[/b] would be easily enough, but [b]f + x = 5[/b] wouldnt be as straightforward - although again, a few simple-ish steps would sort that out.

it really depends on how complex you see these equations getting.
I believe that redbullmarky is suggesting an implementation similar to this:

[code]
<?php
$x = 2;
$evalString = 'x + 2';

echo evaluate($evalString, $x);
        // Output: 4       

function evaluate($str, $x)
{
$str = _prep($str);
$f = false;
eval ('$f = ' . $str . ';');
return $f;
}

function _prep($str){
$str = str_replace('x', '$x', $str);
return $str;
}

?>
[/code]

The _prep function could be extended to handle more advanced input i.e., turning $x^2 to pow($x, 2) etc via regex.  I also agree that writing a script to solve linear equations will be another can of worms, however the code provided should handle the trivial case.

Best,

Patrick
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.