How to Solve a Quadratic Equation in Python


In this example we will show how to solve a quadratic equation in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# computeQuadratic.py

import cmath

def equation(a, b, c, highmiddle=True):
    # Here we need make sure a, b, c is number and a is not zero
    # highmiddle is True for high school,False for middle school
    if not isinstance(a, (int, float, complex)) or abs(a) < 1e-6:
        print('error')
        return
    if not isinstance(b, (int, float, complex)):
        print('error')
        return
    if not isinstance(c, (int, float, complex)):
        print('error')
        return

    # start to calculate
    d = b**2 - 4*a*c
    x1 = (-b + cmath.sqrt(d)) / (2*a)
    x2 = (-b - cmath.sqrt(d)) / (2*a)

    # Here we handle two cases (the calculation result is actual or complex number)  
    if isinstance(x1, complex):
        if highmiddle:
            # here we consider complex number
            x1 = round(x1.real, 3) + round(x1.imag, 3) * 1j
            x2 = round(x2.real, 3) + round(x2.imag, 3) * 1j
            return (x1, x2)
        else:
            # for the level of middle school, just print no answer
            print('no answer')
            return
    # Here we carry three significant digits if the calculation result is actual number
    return (round(x1, 3), round(x2, 3))

def main():
    r = equation(1, 2, 1)
    if isinstance(r, tuple):
        print('x1 = {0[0]}nx2 = {0[1]}'.format(r))

if __name__ == '__main__':
    main()

After running the codes above, we can get these results:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments