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.

Tony
  • 9,672
  • 3
  • 47
  • 75
lain
  • 5
  • 1

2 Answers2

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.

nullUser
  • 1,601
  • 1
  • 12
  • 29
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()

Crawl Cycle
  • 257
  • 2
  • 8