Python Tutorial (33) - Example: Quadratic Equation

Time: Column:Python views:272

Solving a Quadratic Equation

The following example demonstrates how to calculate the solutions of a quadratic equation based on user input:

Example (Python 3.0+):

# Quadratic equation: ax**2 + bx + c = 0
# a, b, c are real numbers provided by the user, with a ≠ 0

# Import the cmath (complex math) module
import cmath

a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# Calculate the discriminant
d = (b**2) - (4*a*c)

# Two solutions
sol1 = (-b - cmath.sqrt(d)) / (2*a)
sol2 = (-b + cmath.sqrt(d)) / (2*a)

print('The solutions are {0} and {1}'.format(sol1, sol2))

When you run this code, the output will be:

Output:

$ python test.py
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

In this example, the program solves a quadratic equation of the form ax2+bx+c=0ax^2 + bx + c = 0, where the coefficients aa, bb, and cc are provided by the user. The discriminant d=b24acd = b^2 - 4ac is used to determine the solutions, and the cmath.sqrt() function is applied to compute the square root. This approach handles complex solutions when necessary.