Skip to Main Content
Blog

Find Roots of a Quadratic Equation in Python

Find Roots of a Quadratic Equation in Python

import cmath  # for complex square roots
import math


def main():
	a = int(input("Enter a: "))
	b = int(input("Enter b: "))
	c = int(input("Enter c: "))

	disc = b * b - 4 * a * c
	twoA = 2.0 * a

	# e.g. x^2 - 6x + 3 = 0
	if disc > 0.0:
		dSqrt = math.sqrt(disc)
		realA = (-b - dSqrt) / twoA
		realB = (-b + dSqrt) / twoA
		print(f"({realA:.3f}, {realB:.3f})")

	# e.g. x^2 - 6x + 12 = 0
	elif disc < 0.0:
		dSqrt = cmath.sqrt(disc)  # complex square root
		rootA = (-b - dSqrt) / twoA
		rootB = (-b + dSqrt) / twoA
		print(
			f"({rootA.real:.0f}{rootA.imag:.3f}i), ({rootB.real:.0f}{rootB.imag:+.3f}i)"
		)

	# e.g. x^2 - 6x + 9 = 0
	else:
		root = -b / twoA
		print(f"({root:.3f}, {root:.3f})")


if __name__ == "__main__":
	main()