Solving Quadratic Equation in Python

 Solving Quadratic Equation in Python


In this blog, we will learn how to solve the Quadratic and polynomial equations or simple quadratic equations in python

Let's first see the nomal convention method that we have learn in school

here we using equation x^2 + 5*x + 6

Code :
import math as m
a = 1
b = 5
c = 6 
x1 = (-b + m.sqrt(b**2-4*a*c))/(2*a)
x2 = (-b - m.sqrt(b**2-4*a*c))/(2*a)
print(x1,x2)

Ouput = -2 ,-3

Shortcut method:
In shorcut method we will call  a special funciton from numpy called polynomial so solve our equations here we using equation x^2 + 5*x + 6 .
Notice in the code i only write coefficient of quadratic equation only and in reverse order. You can also make factoring cubic by using polynomial equations

from numpy import polynomial as p
p1 = p.Polynomial([6,5,1])
p1.roots()


The advantage of using this it can solve any polynomial equations

Suppose if i write this code 

from numpy import polynomial as p
p1 = p.Polynomial([6,0,1])
p1.roots()

Output : array([0.-2.44948974j, 0.+2.44948974j])

the equation here ([6,0,1]) means 6 + x^2

One more example  

from numpy import polynomial as p
p1 = p.Polynomial([3,6,-3,1])
p1.roots()

Output  :  array([-0.40628758+0.j        ,  1.70314379-2.11736477j,
        1.70314379+2.11736477j])

here the equation 3 + 6x -3x^2+ x^3




Post a Comment

0 Comments