Skip to content

Commit d2f7982

Browse files
authored
Update quadratic equations solver (TheAlgorithms#1764)
Use pythons complex number module cmath for the calculation of the roots
1 parent 748702b commit d2f7982

File tree

1 file changed

+21
-23
lines changed

1 file changed

+21
-23
lines changed

maths/quadratic_equations_complex_numbers.py

+21-23
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,36 @@
1-
from math import sqrt
1+
from cmath import sqrt
22
from typing import Tuple
33

44

5-
def QuadraticEquation(a: int, b: int, c: int) -> Tuple[str, str]:
5+
def quadratic_roots(a: int, b: int, c: int) -> Tuple[complex, complex]:
66
"""
77
Given the numerical coefficients a, b and c,
8-
prints the solutions for a quadratic equation, for a*x*x + b*x + c.
8+
calculates the roots for any quadratic equation of the form ax^2 + bx + c
99
10-
>>> QuadraticEquation(a=1, b=3, c=-4)
11-
('1.0', '-4.0')
12-
>>> QuadraticEquation(5, 6, 1)
13-
('-0.2', '-1.0')
10+
>>> quadratic_roots(a=1, b=3, c=-4)
11+
(1.0, -4.0)
12+
>>> quadratic_roots(5, 6, 1)
13+
(-0.2, -1.0)
14+
>>> quadratic_roots(1, -6, 25)
15+
((3+4j), (3-4j))
1416
"""
17+
1518
if a == 0:
16-
raise ValueError("Coefficient 'a' must not be zero for quadratic equations.")
19+
raise ValueError("Coefficient 'a' must not be zero.")
1720
delta = b * b - 4 * a * c
18-
if delta >= 0:
19-
return str((-b + sqrt(delta)) / (2 * a)), str((-b - sqrt(delta)) / (2 * a))
20-
"""
21-
Treats cases of Complexes Solutions(i = imaginary unit)
22-
Ex.: a = 5, b = 2, c = 1
23-
Solution1 = (- 2 + 4.0 *i)/2 and Solution2 = (- 2 + 4.0 *i)/ 10
24-
"""
25-
snd = sqrt(-delta)
26-
if b == 0:
27-
return f"({snd} * i) / 2", f"({snd} * i) / {2 * a}"
28-
b = -abs(b)
29-
return f"({b}+{snd} * i) / 2", f"({b}+{snd} * i) / {2 * a}"
21+
22+
root_1 = (-b + sqrt(delta)) / (2 * a)
23+
root_2 = (-b - sqrt(delta)) / (2 * a)
24+
25+
return (
26+
root_1.real if not root_1.imag else root_1,
27+
root_2.real if not root_2.imag else root_2,
28+
)
3029

3130

3231
def main():
33-
solutions = QuadraticEquation(a=5, b=6, c=1)
34-
print("The equation solutions are: {} and {}".format(*solutions))
35-
# The equation solutions are: -0.2 and -1.0
32+
solutions = quadratic_roots(a=5, b=6, c=1)
33+
print("The solutions are: {} and {}".format(*solutions))
3634

3735

3836
if __name__ == "__main__":

0 commit comments

Comments
 (0)