Write a program to Solve Quadratic Equation in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath # To take input from the users a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) |
Output
The code you provided is a simple Python program that calculates the solutions of a quadratic equation of the form ax^2 + bx + c = 0.
The program starts by importing the cmath
module, which is a standard library that provides mathematical functions for working with complex numbers.
Then, the program uses the input()
function to prompt the user to enter the values of the coefficients a, b and c of the quadratic equation. The user’s input is stored as a string, so it needs to be converted to a float using the float()
function.
Next, the program calculates the discriminant of the equation, which is the value under the square root in the quadratic formula, by using the formula (b^2) – (4ac) and assigns the result to the variable d
.
Then, the program calculates two solutions of the equation, using the quadratic formula (-b ± √(b^2 – 4ac)) / 2a, by using the cmath.sqrt() function to find square root of d and assigns the result to the variables sol1
and sol2
respectively.
Finally, the print()
function is used to output the solutions of the quadratic equation to the console. The format()
method is used to insert the values of sol1
and sol2
into the string that is passed to the print()
function.
The output will depend on the input provided by the user. For example, if the user inputs a=1, b=-5 and c=6, the output will be “The solution are (3+0j) and (2+0j)”
Take your time to comment on this article.