Jump to content

Quadratics


Bulbe

Recommended Posts

Hey everyone,

i've been doing a work in math and it should be about solving quadratics in php. Well, my dictonary says that quadratics mean all this stuff, not only ax2+bx+c. So my question is, do you think it would be possible to make this in php ? You would enter the quadratic and it would show its roots

 

Best regard, Bulb

Link to comment
https://forums.phpfreaks.com/topic/99742-quadratics/
Share on other sites

Was bored:

 

<?php
$eqn = '-2x^2+32-2x=3x+2x-32-x^2';
function rearrange($eqn){
    $sides = explode('=',$eqn);
    $coefficients = array();
    foreach($sides as $k => $v){
        preg_match_all('%(\-|\+)?[0-9x^]+%s',$v,$terms);

        foreach($terms[0] as $v2){
            //work out which term is being used
            if(strpos($v2, 'x^2') !== false){
                $key = 0;
            }elseif(strpos($v2, 'x') !== false){
                $key = 1;
            }else{
                $key = 2;
            }
		//work out the coefficient
		preg_match('%^(\-|\+)?[0-9]+%s',$v2,$matches);
		if(empty($matches)){
		    if($v2[0] == '-'){
		        $num = -1;
		    }else{
		        $num = 1;
		    }
		}else{
		    $num = $matches[0];
		}
		@$coefficients[$k][$key] += $num;//+= because terms may not be collected
        }
    }
    for($x=0;$x<=2;$x++){
        //collect terms. Surpress error since coeffiecent may not be set
        @$rearranged[$x] = $coefficients[0][$x] - $coefficients[1][$x];
    }
    return $rearranged;
    

}
function solve($coefficients){
    list($a,$b,$c) = $coefficients;
    $discriminant = pow($b,2) - 4*$a*$c;
    if($discriminant > 0){
        $roots[0] = (-$b + sqrt($discriminant))/(2*$a);
        $roots[1] = (-$b - sqrt($discriminant))/(2*$a);        
    }elseif($discriminant == 0){
        $roots[0] = -$b/(2*$a);
    }else{
        $real = -$b/(2*$a);
        $imaginary = sqrt(-$discriminant)/(2*$a);
        $roots[0] = $real.' + '.$imaginary.'i';
        $roots[1] = $real.' - '.$imaginary.'i';
    }
    return $roots;
}
print_r(solve(rearrange($eqn)));
?>

 

Will work as long as there's nothing unexpected in the input.

Link to comment
https://forums.phpfreaks.com/topic/99742-quadratics/#findComment-510632
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.