Solving a quadratic equation in Python

Introduction

Quadratic equations are equations of the form

a*x^2 + b*x + c

x^2 and x are implied by default, so it is enough to set a, b and c - and it immediately becomes clear what the quadratic equation looks like.

Example solution

First of all, let us check that a, b and c are numbers

from math import sqrt def quadratic_solve(a ,b, c): if not all( map( lambda p: isinstance(p, (int, float)), (a, b, c) ) ): raise TypeError("Not valid argument type") print("Types are OK") if a == 0: if b == 0: # a and b are 0: no solution return None, None return -c / b, None d = b ** 2 - 4 * a * c if d < 0: return None, None d_root = sqrt(d) divider = 2 * a x1 = (-b + d_root) / divider x2 = (-b - d_root) / divider if d == 0: x2 = None elif x2 > x1: x1, x2 = x2, x1 return x1, x2

Functions used

Here I used the functions: all() , map() and the lambda function

If something is unclear, follow the links to the functions or visit the section «Functions»

Examples of equations and their roots

To check, you can use the following equations:

With one root

x^2 - 2x + 1
a = 1, b = -2, c = 1
Roots: 1, None

5x^2 + 7x
a = 5, b = 7, c = 0
Roots: 0, None

With two roots

x^2 + x -6
a = 1, b = 1, c = -6
Roots: -3, 2

Without solutions

x^2 + x + 9
a = 1, b = 1, c = +9
Roots: None, None

Article author: Andrei Olegovich

Banner image