PHP algebraic equation function
Recently while cleaning out some of my old files I came across a PHP class project which I, like every programmer, had started but never finished. I started this class about 3 years ago with intentions of building a larger library of functions which could solve different Leaving Cert maths problems. I never was the best at maths and so I combined something I love, programming, with something I needed to improve, maths! I figured that if I could program a machine to solve the equations I could do it myself. Even though I only wrote one function, it helped me dramatically. Here is a live AJAX demo of the code, and below that is the source code, though I wrote it almost 3 years so do forgive any mistakes or bad code. Just thought I would share it.
You most put spaces between numbers/operators like in the example below for it to work. Also it will only work with X not any other letter. – NOTE: This code is 3 years old
Source Code
class algebra{
public function solve_x($sum)
{
// checks if sum exists
if($sum)
{
$sum = str_replace("\n", "{line_break}", $sum);
$sum = split('{line_break}',$sum);
$chr_no = strlen($sum[0]);
$sum_array = split(' ',$sum[0]);
$i = 0;
while($i < $chr_no)
{
$haystack_operators = array('+','-');
// check to see if $sum_array[$i] is a number//
if(is_numeric($sum_array[$i])){
$a = $i - 1;
$haystack_operators = array('=');
if(!in_array($sum_array[$a],$haystack_operators ))
{
// changes the sign
if($sum_array[$a] == "-")
{
$sign = "+";
}
else
{
$sign = "-";
};
$cal[$i] = $sign.$sum_array[$i];
}
else
{
$theSumOf = $sum_array[$i];
};
};
$needle_notation = 'x,X';
if(strpbrk($sum_array[$i],$needle_notation))
{
// removes the x from the equestion eg 2x -> 2
$diviser[$i] = str_replace($needle_notation," ",$sum_array[$i]);
};
$i++;
};
if($cal)
{
$calu = array_sum($cal);
};
if($diviser)
{
$diviser = array_sum($diviser);
};
$theSumOf = $theSumOf+$calu;
if($diviser)
{
$ans = $theSumOf/$diviser;
};
return $ans;
};
}// End of method
}// End of class
No related posts.



0 Responses to “PHP algebraic equation function”