0

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:

screen shot of the output on pycharm

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.

2
  • The result is a complex number, the "+" between the 2 numbers indicates the real and imaginary part added together. Commented Nov 4, 2020 at 0:05
  • Ah of course, how stupid of me. Thank you! Commented Nov 4, 2020 at 11:13

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I split the program into several functions:

  • calculation of determinant
  • the quadratic formula
  • get user input
  • print result

And it is fine.

import cmath def cal_determinant(a, b, c): return b * b - 4 * a * c def quadratic_formula(a, b, c): det = cal_determinant(a, b, c) sqrt_det = cmath.sqrt(det) x1 = (-b - sqrt_det) / (2 * a) x2 = (-b + sqrt_det) / (2 * a) return x1, x2 def get_user_input(): coeff_list = [] for coeff_name in ["a", "b", "c"]: v = input(f"{coeff_name}: ") v = float(v) coeff_list.append(v) return coeff_list def print_roots(x1, x2): print(f"x1: {x1}") print(f"x2: {x2}") def main(): a, b, c = get_user_input() x1, x2 = quadratic_formula(a, b, c) print_roots(x1, x2) main() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.