...

View Full Version : Algebra



PureMisery
01-02-2006, 05:58 AM
Is there a way to get php to solve for a variable?

Ex,
1.1x=110
output to screen would be what x is

ralph l mayo
01-02-2006, 07:46 AM
Brute force? I'm pretty sure that's how the fancy calculators do it.



function solveForX($equation, $answer, $min = null, $max = null)
{
$min = ($min == null) ? -mt_getrandmax() : $min;
$max = ($max == null) ? mt_getrandmax() : $max;
$last['guess'] = null;

while (true)
{
eval('$attempt = ' . str_replace('x', ($guess = mt_rand($min, $max)), $equation) . ';');
if ($attempt == $answer)
{
return($guess);
}
if ($last['guess'] != null)
{
$diff = abs($answer - $attempt);
if ($diff > $last['diff'])
{
if ($guess > $last['guess'])
{
$max = $guess - 1;
}
else
{
$min = $guess + 1;
}
}
}
$last['guess'] = $guess;
$last['diff'] = abs($answer - $attempt);
}
}

echo solveForX('x+(x*.1)', 110);


Note this is oversimplified and will fall into infinite loops on discontinuous functions and functions with noninteger answers. The latter problem is pretty easily resolvable, the former maybe not so much.

Also, it'd probably be neater if it was refactored to use recursion, another exercise I'll leave to the reader. :p

Kurashu
01-02-2006, 07:45 PM
There's some good classes that help handle this.

http://www.phpclasses.org/browse/class/65.html

Check there for some.

PureMisery
01-03-2006, 04:12 AM
There's some good classes that help handle this.

http://www.phpclasses.org/browse/class/65.html

Check there for some.
Thanks, I'll go look around there now.


<---edit--->
I found one that I think will do what I need. But how do use the files?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum