How to Solve Quadratic Equations Using Python?

Estimated read time 2 min read

To solve a quadratic equation of the form ax^2 + bx + c = 0, where a, b, and c are constants and x is the variable, you can use the quadratic formula:

x = (-b ± sqrt(b^2 - 4ac)) / 2a

Here is an example of how to solve a quadratic equation using Python:

import math

def solve_quadratic(a, b, c):
    discriminant = b**2 - 4*a*c
    if discriminant < 0:
        return None # no real solutions
    elif discriminant == 0:
        return -b / (2*a) # one real solution
    else:
        root1 = (-b + math.sqrt(discriminant)) / (2*a)
        root2 = (-b - math.sqrt(discriminant)) / (2*a)
        return (root1, root2) # two real solutions

# test the function with a sample input
a = 1
b = -5
c = 6
print(solve_quadratic(a, b, c))

In this solution, we define a function solve_quadratic that takes the coefficients a, b, and c of a quadratic equation as input. The function first calculates the discriminant b^2 - 4ac and checks whether it is negative (no real solutions), zero (one real solution), or positive (two real solutions).

If the discriminant is negative, the function returns None to indicate that there are no real solutions. If the discriminant is zero, the function returns the single real solution -b / 2a. If the discriminant is positive, the function calculates the two real solutions using the quadratic formula and returns them as a tuple.

In the main part of the script, we test the function with a sample input coefficients a, b, and c and print out the result.

To use this code with other inputs, simply replace a, b, and c with the desired coefficients. Note that this solution assumes that the input coefficients are valid and non-zero. You may want to add additional error checking to handle these cases.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply