(Algebra: solve quadratic equations) The two roots of a quadratic equation, for example, can be obtained using the following formula:
is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative,the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display one root. Otherwise, display The equationhas no real roots. Here are some sample runs.
Enter a, b, c: 1.0, 3, 1
The roots are -0.381966 and -2.61803
Enter a, b, c: 1, 2.0, 1
The root is -1
Enter a, b, c: 1, 2, 3
The equation has no real roots
Executable code:
#read the coefficients
a=eval(input("Enter coefficient a:"))
b=eval(input("Enter coefficient b:"))
c=eval(input("Enter coefficient c:"))
#calculate the discriminant
discriminant=b*b-4*a*c;
#Condition to check the discriminant whether it is greater than or less than or equal
if(discriminant>0):
root1= (-b+(discriminant**0.5))/(2*a);
root2=(-b-(discriminant**0.5))/(2*a);
print("The roots are ",format(root1, ".6f"),format(root2, ".6f"))
elif(discriminant==0):
root1=root2=-b/(2*a);
print("The root is",root1)
else:
print("The equation has no real roots")
Output:
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Enter coefficient a:1.0
Enter coefficient b:3
Enter coefficient c:1
The roots are -0.381966 -2.618034
>>> ================================ RESTART ================================
>>>
Enter coefficient a:1
Enter coefficient b:2.0
Enter coefficient c:1
The root is -1.0
>>> ================================ RESTART ================================
>>>
Enter coefficient a:1
Enter coefficient b:2
Enter coefficient c:3
The equation has no real roots
>>>