Home > Backend Development > PHP Tutorial > How to find the roots of a quadratic equation in PHP? _PHP Tutorial

How to find the roots of a quadratic equation in PHP? _PHP Tutorial

WBOY
Release: 2016-07-13 10:33:51
Original
3084 people have browsed it

Today someone asked a math question, 4x+1/x=2, what is x? Convert the equation, 4x2 + 1 = 2x, and then 4x2 - 2x + 1 =0, which is actually a quadratic equation problem. I haven’t done these things in a long time, and I’m a high school teacher in mathematics. Fortunately, I can write a program. Let's use the program to find the roots of this equation.

<? 
//ax*x bx c=0;  一元二次方程一般形式  
  
//系数设定  
$a = 2;  
$b = 3;  
$c = 0;  
echo '一元二次方程为';
echo $a.'x2'.'+'.$b.'x'.'+'.$c;
  
//求根的函数 
function get_root($a,$b,$c) 
{ 
	//放根的数组  
	$x=0;  
	$x=array();  
	if($a==0) 
	{ 
  		if($b==0) 
     	if($c==0) 
        { 
        	$x[0]=0; 
        	$x[1]="no root"; 
        } 
      	else 
        { 
        	$x[0]="no root"; 
        	$x[1]="no root"; 
        } 
  		else if($b!=0) 
     	{ 
      		$x[0]=(0-$c)/$b; 
      		$x[1]="no root"; 
     	} 
	} 
	else 
	{ 
		//标志  
  		$flg=$b*$b-4*$a*$c;  
		//△ >0 两个不同的根  
  		if($flg >0)  
    	{  
     		$x[0]=((0-$b)+sqrt($flg))/2/$a;  
     		$x[1]=((0-$b)-sqrt($flg))/2/$a;  
    	}  
  		else if($flg==0)//△=0 两个相同的根  
    	{  
    		$x[0]=(0-$b)/2/$a;  
    		$x[1]=(0-$b)/2/$a;  
    	}  
  		else  // 无根  
    	{  
    		$x[0]="no root";  
    		$x[1]="no root";  
    	}  
  	} 
  	return $x; 
} 
  
//验证代码 参数为顶部设置的a b c  的值,可自行修改测试 
$root=array(); 
$root=get_root($a,$b,$c); 
echo " <pre class="brush:php;toolbar:false">求得根: <br>"; 
print_r($root); 
echo " <pre class="brush:php;toolbar:false">"; 
  
?>
Copy after login

The result of running the program is:

一元二次方程为2x2+3x+0
求得根: 
Array
(
    [0] => 0
    [1] => -1.5
)
Copy after login

Back to the original question, after calculation by the program, the result is:

一元二次方程为4x2+-2x+1
求得根: 
Array
(
    [0] => no root
    [1] => no root
)
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752401.htmlTechArticleToday someone asked a math problem, 4x+1/x=2, what is x. Convert the equation, 4x2 + 1 = 2x, and then 4x2 - 2x + 1 =0, which is actually a quadratic equation problem. Long time no see...
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template