Quadratic equation in Python
Write a Program in Python to solve quadratic equations.
The formula of Quadratic equation
ax2+bx+c=0
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# import complex math module import cmath FistNumber = float(input('Enter FistNumber: ')) SecondNumber = float(input('Enter SecondNumber: ')) ThirdNumber = float(input('Enter ThirdNumber: ')) # calculate the discriminant ThirdNumber = (SecondNumber**2) - (4*FistNumber*ThirdNumber) # find two solutions T4tutorials_Result1 = (-SecondNumber-cmath.sqrt(ThirdNumber))/(2*FistNumber) T4tutorials_Result2 = (-SecondNumber+cmath.sqrt(ThirdNumber))/(2*FistNumber) print('The solution are {0} and {1}'.format(T4tutorials_Result1,T4tutorials_Result2)) |
Output
Enter FistNumber: 9
Enter SecondNumber: 3
Enter ThirdNumber: 4
The solution are (-0.16666666666666666-0.6454972243679028j) and (-0.16666666666666666+0.6454972243679028j)
Second Way: The direct formula of Quadratic equation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# Python program to find roots of quadratic equation import math # function for finding roots def T4tutorials(FirstNumber, SecondNumber, ThirdNumber): dis_form = SecondNumber * SecondNumber - 4 * FirstNumber * ThirdNumber SquareRootValue = math.sqrt(abs(dis_form)) if dis_form > 0: print(" real and different roots ") print((-
SecondNumber + SquareRootValue) / (2 * FirstNumber)) print((-SecondNumber - SquareRootValue) / (2 * FirstNumber)) elif dis_form == 0: print(" real and same roots") print(-SecondNumber / (2 * FirstNumber)) else: print("Complex Roots") print(- SecondNumber / (2 * FirstNumber), " + i", SquareRootValue) print(- SecondNumber / (2 * FirstNumber), " - i", SquareRootValue) FirstNumber = int(input('Enter FirstNumber:')) SecondNumber = int(input('Enter SecondNumber:')) ThirdNumber = int(input('Enter ThirdNumber:')) # If FirstNumber is 0, then incorrect equation if FirstNumber == 0: print("Input correct quadratic equation") else: T4tutorials(FirstNumber, SecondNumber, ThirdNumber) |
Output
Enter FirstNumber:22
Enter SecondNumber:44
Enter ThirdNumber:77
Complex Roots
-1.0 + i 69.57010852370435
-1.0 – i 69.57010852370435