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
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
Share on other sites

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.