Write a function roots(a, b, c) that takes the coefficients of a quadratic equation in standard form as parameters and returns the real roots of quadratic equation. Test this function in the main program with at least the following values:
a b c roots
1 -4 4 2 and 2
1 3 -5 1.19 and -4.19
Assistant
Here's the implementation of the roots function for solving a quadratic equation and testing it with the example values provided:
python
import math
def roots(a, b, c):
"""
Compute the real roots of a quadratic equation ax^2 + bx + c = 0.
Parameters:
a (float): Coefficient of x^2
b (float): Coefficient of x
c (float): Constant term
Returns:
tuple: The real roots of the quadratic equation (or the double root for the case of a perfect square trinomial).
Returns a tuple with two identical values if there is one real root.
"""
discriminant = b**2 - 4*a*c # Calculate the discriminant (b^2 - 4ac)
if discriminant < 0:
# No real roots exist
return None
elif discriminant == 0:
# One real root (double root)
root = -b / (2 * a)
return (root, root)
else:
# Two real roots
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return (root1, root2)
# Main program to test the function
def main():
# Test cases
test_cases = [
(1, -4, 4), # Example 1: Discriminant = 0, Roots: 2 & 2
(1, 3, -5) # Example 2: Discriminant > 0, Roots: 1.19 & -4.19
]
print(f"{'a':>5} {'b':>5} {'c':>5} {'roots':>20}")
print("-" * 35)
for a, b, c in test_cases:
result = roots(a, b, c)
# Format the output
if result is None:
root_output = "No real roots"
elif result[0] == result[1]: # If it's a double root
root_output = f"{result[0]:.2f} and {result[1]:.2f} (double root)"
else: # Two distinct roots
root_output = f"{result[0]:.2f} and {result[1]:.2f}"
print(f"{a:>5} {b:>5} {c:>5} {root_output:>20}")
# Run the main program
main()
Explanation:
Function roots:
The discriminant of a quadratic equation ( b^2 - 4ac ) is used to determine the nature of the roots:
( \text{discriminant} > 0 ): Two distinct real roots.
( \text{discriminant} = 0 ): One double root (both roots are the same).
( \text{discriminant} < 0 ): No real roots (complex roots ignored in this implementation).
The formula for the roots is applied depending on the discriminant:
[
root_1 = \frac{-b + \sqrt{d}}{2a}, \quad root_2 = \frac{-b - \sqrt{d}}{2a}
]
Output:
Outputs the test results in a table format.
Output for the given values:
code
a b c roots
-----------------------------------
1 -4 4 2.00 and 2.00 (double root)
1 3 -5 1.19 and -4.19
This function works for any quadratic equation with real solutions, and the main program demonstrates its correct application for your test cases!