2020-09-23 11:30:13 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2020-02-19 18:45:55 +00:00
|
|
|
from cmath import sqrt
|
2019-08-06 00:22:34 +00:00
|
|
|
|
2019-08-06 19:32:27 +00:00
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
|
2019-08-06 19:32:27 +00:00
|
|
|
"""
|
|
|
|
Given the numerical coefficients a, b and c,
|
2020-02-19 18:45:55 +00:00
|
|
|
calculates the roots for any quadratic equation of the form ax^2 + bx + c
|
2019-08-06 19:32:27 +00:00
|
|
|
|
2020-02-19 18:45:55 +00:00
|
|
|
>>> quadratic_roots(a=1, b=3, c=-4)
|
|
|
|
(1.0, -4.0)
|
|
|
|
>>> quadratic_roots(5, 6, 1)
|
|
|
|
(-0.2, -1.0)
|
|
|
|
>>> quadratic_roots(1, -6, 25)
|
|
|
|
((3+4j), (3-4j))
|
2019-08-06 00:22:34 +00:00
|
|
|
"""
|
2020-02-19 18:45:55 +00:00
|
|
|
|
2019-08-06 19:32:27 +00:00
|
|
|
if a == 0:
|
2020-02-19 18:45:55 +00:00
|
|
|
raise ValueError("Coefficient 'a' must not be zero.")
|
2019-08-06 19:32:27 +00:00
|
|
|
delta = b * b - 4 * a * c
|
2020-02-19 18:45:55 +00:00
|
|
|
|
|
|
|
root_1 = (-b + sqrt(delta)) / (2 * a)
|
|
|
|
root_2 = (-b - sqrt(delta)) / (2 * a)
|
|
|
|
|
|
|
|
return (
|
|
|
|
root_1.real if not root_1.imag else root_1,
|
|
|
|
root_2.real if not root_2.imag else root_2,
|
|
|
|
)
|
2019-08-06 19:32:27 +00:00
|
|
|
|
2019-08-06 00:22:34 +00:00
|
|
|
|
2019-08-06 19:32:27 +00:00
|
|
|
def main():
|
2020-02-19 18:45:55 +00:00
|
|
|
solutions = quadratic_roots(a=5, b=6, c=1)
|
|
|
|
print("The solutions are: {} and {}".format(*solutions))
|
2019-08-06 10:14:23 +00:00
|
|
|
|
|
|
|
|
2019-08-06 19:32:27 +00:00
|
|
|
if __name__ == "__main__":
|
2019-08-06 00:22:34 +00:00
|
|
|
main()
|