PHP Program - Find Roots of a Quadratic Equation
A standard form of a quadratic equation is:
ax2 + bx + c = 0
Where:
a, b and c are real numbers and a ≠ 0.
Roots of the equation are:
For Example:
The roots of equation x2 + 5x + 4 = 0 is
The roots of the equation will be imaginary if D = b2 - 4ac < 0. For example - the roots of equation x2 + 4x + 5 = 0 will be
Example: Calculate roots of a Quadratic equation
In the example below, a function called roots is created which takes a, b and c as arguments to calculate the roots of the equation ax2 + bx + c = 0.
<?php function roots($a, $b, $c) { $D = $b*$b - 4*$a*$c; if ($D >= 0){ $x1 = (-$b + sqrt($D))/(2*$a); $x2 = (-$b - sqrt($D))/(2*$a); echo "Roots are: $x1, $x2 \n"; } else { $x1 = -$b/(2*$a); $x2 = sqrt(-$D)/(2*$a); echo "Roots are: $x1 ± $x2 i \n"; } } echo "Equation is x*x+5x+4=0\n"; roots(1,5,4); echo "\nEquation is x*x+4x+5=0\n"; roots(1,4,5); ?>
The above code will give the following output:
Equation is x*x+5x+4=0 Roots are: -1, -4 Equation is x*x+4x+5=0 Roots are: -2 ± 1 i
Recommended Pages
- PHP Program - To Check Prime Number
- PHP Program - Bubble Sort
- PHP Program - Selection Sort
- PHP Program - Maximum Subarray Sum
- PHP Program - Reverse digits of a given Integer
- PHP - Swap two numbers
- PHP Program - Fibonacci Sequence
- PHP Program - Insertion Sort
- PHP Program - Find Factorial of a Number
- PHP Program - Find HCF of Two Numbers
- PHP Program - Merge Sort
- PHP Program - Shell Sort
- Stack in PHP
- Queue in PHP
- PHP Program - Find LCM of Two Numbers
- PHP Program - To Check Whether a Number is Palindrome or Not
- PHP Program - To Check Whether a String is Palindrome or Not
- PHP Program - Heap Sort
- PHP Program - Quick Sort
- PHP - Swap Two Numbers without using Temporary Variable