The Quadratic Equation Calculator and the code that I used didn't work well. There are some errors on the code.
I already tried with basic numbers, like 1/2/3. No equation. Still the code doesn't works. The things that actually work is putting the variable only and that's all. After I press enter to see what is the answer, it said that my code has some errors on it.
print ("Quadratic Equation Calculator")
import math
print ("Enter the first variable : ")
first = float(input(''))
print ("Enter the second variable : ")
second = float(input(''))
print ("Enter the third variable : ")
third = float(input(''))
Answer1 = ((-1 * second) - math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)
Answer2 = ((-1 * second) + math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)
print (Answer1)
print (Answer2)
I expect to answer the questions properly and this equation calculator can be used for real equations and using variables. x square and 3x and something like that.
In python x ^ 2, can be x ** 2, x * x or pow(x, 2). Others have given you good suggestions, and I would like to add a few. The Quadratic Equation: ax^2 + bx + c = 0 (Adjust to make the equation equal zero!) has polynomial terms ax^2, bx, c; whose coefficients are a, b. And c being the constant term. then the Quadratic formulae: (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a; Solves for x.
All of the above appears rightly in your code However, you will have trouble if the solutions dwell in complex numbers set {C}.
This can be easily tackled by gauging the "discriminant".
The discriminant is b^2 - 4ac, and
Considering above conditions, the code should look so:
import math
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
discriminant = pow(b, 2) - 4.0 * a * c
if discriminant == 0:
root1 = root2 = (-1 * b) / (2 * a)
elif discriminant < 0:
root1 = ((-1 * b) - math.sqrt(-discriminant) * 1j) / (2 * a)
root2 = ((-1 * b) + math.sqrt(-discriminant) * 1j) / (2 * a)
else:
root1 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)
root2 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)
print (root1)
print (root2)
Similar SO answers: https://stackoverflow.com/a/49837323/8247412
Below I have altered the code in favour of pythonic programming, as numpy can find roots of polynomial (quadratic and higher order) equations with prowess. numpy.roots
import numpy as np
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
coeffs = [a, b, c] # or d, e and so on..
roots = np.roots(coeffs)
print (roots)