I am making a program that asks the user to input values for a, b and c which are then used to compute the roots using the quadratic formula. The only problem I have is that python treats a and the square root term as two strings and they are not actually added. The + between them is printed out.
Here is my code:
import cmath
def cubic_formula(a, b, c):
print("x1: " + str((-b-cmath.sqrt(b**2-4*a*c))/(2*a)))
print("x2: " + str((-b+cmath.sqrt(b ** 2 - 4 * a * c)) / (2 * a)))
a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: "))
cubic_formula(a, b, c)
And here is the output, illustrating the problem I just described:
I don't know how to make it so that the plus-sign results in an actual addition of the two numbers. Removing the str() and having no strings inside print() did not change anything.
You are witnessing complex numbers, not strings. When the discriminant b*b-4*a*c
is negative, the solution is not real valued. The imaginary unit is denoted j
in Python and complexes print like (a+bj)
in Python.
You may want to check if the discriminant is positive before computing, and use the math.sqrt
function, which returns a float, instead of the cmath.sqrt
function, which returns a complex.
Also note you called the function cubic_formula
, but are calculating quadratic_formula
.