Python program to solve quadratic equation

Python program to solve quadratic equation

A quadratic equation is given by:

ax2+bx+c=0

The solutions (or roots) of this equation can be found using the quadratic formula:

x=2a−b±b2−4ac​​

Here's a Python program that takes the coefficients a, b, and c as inputs and prints the solutions:

import cmath def solve_quadratic(a, b, c): # Calculate the discriminant D = cmath.sqrt(b**2 - 4*a*c) # Calculate the two solutions x1 = (-b + D) / (2*a) x2 = (-b - D) / (2*a) return (x1, x2) # Input coefficients a = float(input("Enter the coefficient a: ")) b = float(input("Enter the coefficient b: ")) c = float(input("Enter the coefficient c: ")) # Get solutions x1, x2 = solve_quadratic(a, b, c) # Display solutions print(f"Solutions are: {x1} and {x2}") 

Note:

  1. We use the cmath module (complex math) to handle cases where the discriminant b2−4ac is negative, which would result in complex solutions.
  2. If the discriminant is zero, the quadratic equation has one real solution (i.e., a repeated root). If the discriminant is positive, the equation has two distinct real roots. If it's negative, the equation has two distinct complex roots.

More Tags

text-editor command perforce netty ipv6 brokeredmessage breakpoints mouse comparator ibatis

More Programming Guides

Other Guides

More Programming Examples