1. Introduction
Solving quadratic equations is a fundamental problem in algebra. In Python, we can create a program to find the roots of a quadratic equation of the form ax^2 + bx + c = 0 using the quadratic formula.
The roots of a quadratic equation ax^2 + bx + c = 0 are given by the formulas:
(-b + sqrt(b^2 - 4ac)) / (2a)
(-b - sqrt(b^2 - 4ac)) / (2a)
These roots can be real or complex numbers depending on the discriminant b^2 - 4ac.
2. Program Steps
1. Define the coefficients a, b, and c of the quadratic equation.
2. Calculate the discriminant b^2 - 4ac.
3. Determine the nature of the roots based on the discriminant.
4. Calculate and print the roots using the appropriate formula.
3. Code Program
import cmath # Import complex math module
# Function to calculate roots of quadratic equation
def find_roots(a, b, c):
# Calculate the discriminant
discriminant = cmath.sqrt(b**2 - 4*a*c)
# Calculate two solutions
root1 = (-b + discriminant) / (2*a)
root2 = (-b - discriminant) / (2*a)
return root1, root2
# Coefficients of the quadratic equation
a_coeff = 1
b_coeff = 5
c_coeff = 6
# Calculate the roots
root_1, root_2 = find_roots(a_coeff, b_coeff, c_coeff)
# Print the results
print(f"The roots of the quadratic equation are: {root_1} and {root_2}")
Output:
The roots of the quadratic equation are: (-2+0j) and (-3+0j)
Explanation:
1. cmath library is imported to handle complex square roots.
2. find_roots function is defined to take the coefficients a, b, and c as arguments.
3. The discriminant is calculated using b2 - 4ac, and cmath.sqrt is used to handle complex results.
4. root1 and root2 are calculated using the quadratic formula.
5. The coefficients of the equation a_coeff, b_coeff, and c_coeff are defined with the values 1, 5, and 6, representing ax^2 + bx + c.
6. The find_roots function is called with these coefficients and returns two roots.
7. The roots are printed, which are (-2+0j) and (-3+0j) indicating two real roots at -2 and -3.
8. The output is formatted with an f-string to clearly present the roots.
Comments
Post a Comment
Leave Comment