Joshua
Joshua

Reputation: 33

How to solve for imaginary numbers correctly in a quadratic in python?

I am trying to create a quadratic solver where it will tell me the values of x. It works flawlessly until one of the answers would be an imaginary number. How do I make it so the program doesn't crash every time and actually gives the correct answer in terms of i?

import math
print()
a = input("Coefficient of a: ")
a = float(a)
b = input("Coefficient of b: ")
b = float(b)
c = input("Coefficient of c: ")
c = float(c)

x_1 = (-b + math.sqrt(b ** 2 - (4 * a * c))) / 2 * a
x_2 = (-b - math.sqrt(b ** 2 - (4 * a * c))) / 2 * a
print()
print(f" X = {x_1} or {x_2}")
print()

Upvotes: 0

Views: 981

Answers (3)

Seyed_Ali_Mohtarami
Seyed_Ali_Mohtarami

Reputation: 1164

you can use sympy this:example(Equation of the second and third degree and ...)

import sympy as sp
x = sp.Symbol("x")
print(sp.solve(x ** 4 - 1, x))

output:

[-1, 1, -I, I]

pip install sympy :https://pypi.org/project/sympy/

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195508

You can use complex() instead of float():

a = input("Coefficient of a: ")
a = complex(a)
b = input("Coefficient of b: ")
b = complex(b)
c = input("Coefficient of c: ")
c = complex(c)

x_1 = (-b + (b ** 2 - (4 * a * c))**0.5) / 2 * a
x_2 = (-b - (b ** 2 - (4 * a * c))**0.5) / 2 * a
print()
print(f" X = {x_1} or {x_2}")
print()

Prints (for example):

Coefficient of a: 3+2j
Coefficient of b: 1
Coefficient of c: -2-1j

 X = (3.1748906833227015+8.198076043446118j) or (-6.174890683322701-10.198076043446118j)

Upvotes: 1

vvvvv
vvvvv

Reputation: 31720

Check the value of b ** 2 - (4 * a * c). If it's negative, you have imaginary solutions.

So your code becomes:

import math
print()
a = input("Coefficient of a: ")
a = float(a)
b = input("Coefficient of b: ")
b = float(b)
c = input("Coefficient of c: ")
c = float(c)

delta = b ** 2 - (4 * a * c)
if delta >= 0:
    x_1 = (-b + math.sqrt(b ** 2 - (4 * a * c))) / 2 * a
    x_2 = (-b - math.sqrt(b ** 2 - (4 * a * c))) / 2 * a
    print()
    print(f" X = {x_1} or {x_2}")
    print()
else:
    print("The 2 solutions are imaginary:")
    real = -b
    imag = abs(math.sqrt(-delta) / (2 * a))
    print(f" X = {real} + i*{imag} or {real} - i*{imag}")

Upvotes: 0

Related Questions