|
1 |
| -from math import sqrt |
| 1 | +from cmath import sqrt |
2 | 2 | from typing import Tuple
|
3 | 3 |
|
4 | 4 |
|
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]: |
6 | 6 | """
|
7 | 7 | 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 |
9 | 9 |
|
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)) |
14 | 16 | """
|
| 17 | + |
15 | 18 | if a == 0:
|
16 |
| - raise ValueError("Coefficient 'a' must not be zero for quadratic equations.") |
| 19 | + raise ValueError("Coefficient 'a' must not be zero.") |
17 | 20 | 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 | + ) |
30 | 29 |
|
31 | 30 |
|
32 | 31 | 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)) |
36 | 34 |
|
37 | 35 |
|
38 | 36 | if __name__ == "__main__":
|
|
0 commit comments