Write a function to compute the roots of a mathematical equation of the form \begin{align} ax^{2} + bx + c = 0. \end{align} Your function should be sensitive enough to adapt to situations in which a user might accidentally set $a=0$, or $b=0$, or even $a=b=0$. For example, if $a=0, b\neq 0$, your function should print a warning and compute the roots of the resulting linear function. It is up to you on how to handle the function header: feel free to use default keyword arguments, variable positional arguments, variable keyword arguments, or something else as you see fit. Try to make it user friendly.
Your function should return a tuple containing the roots of the provided equation.
Hint: Quadratic equations can have complex roots of the form $r = a + ib$ where $i=\sqrt{-1}$ (Python uses the notation $j=\sqrt{-1}$). To deal with complex roots, you should import the cmath library and use cmath.sqrt when computing square roots. cmath will return a complex number for you. You could handle complex roots yourself if you want, but you might as well use available libraries to save some work.
In [2]:
import cmath
def find_root(a,b,c):
if (a==0 and b==0 and c==0):
print("warning!\n x has infinite numbers")
return()
elif (a==0 and b==0 and c!=0):
print("error!\n no x")
return()
elif (a==0 and b!=0):
print("warning!\n x=",-c/b)
return(-c/b)
else:
x1=(-b+cmath.sqrt(b*b-4*a*c))/(2*a)
x2=(-b-cmath.sqrt(b*b-4*a*c))/(2*a)
print("x1=",x1)
print("x2=",x2)
return(x1,x2)
find_root(0,0,0)
Out[2]:
In [ ]: