mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-03-27 17:06:44 +00:00
Update quadratic equations solver (#1764)
Use pythons complex number module cmath for the calculation of the roots
This commit is contained in:
parent
748702b461
commit
d2f7982a4e
@ -1,38 +1,36 @@
|
|||||||
from math import sqrt
|
from cmath import sqrt
|
||||||
from typing import Tuple
|
from typing import Tuple
|
||||||
|
|
||||||
|
|
||||||
def QuadraticEquation(a: int, b: int, c: int) -> Tuple[str, str]:
|
def quadratic_roots(a: int, b: int, c: int) -> Tuple[complex, complex]:
|
||||||
"""
|
"""
|
||||||
Given the numerical coefficients a, b and c,
|
Given the numerical coefficients a, b and c,
|
||||||
prints the solutions for a quadratic equation, for a*x*x + b*x + c.
|
calculates the roots for any quadratic equation of the form ax^2 + bx + c
|
||||||
|
|
||||||
>>> QuadraticEquation(a=1, b=3, c=-4)
|
>>> quadratic_roots(a=1, b=3, c=-4)
|
||||||
('1.0', '-4.0')
|
(1.0, -4.0)
|
||||||
>>> QuadraticEquation(5, 6, 1)
|
>>> quadratic_roots(5, 6, 1)
|
||||||
('-0.2', '-1.0')
|
(-0.2, -1.0)
|
||||||
|
>>> quadratic_roots(1, -6, 25)
|
||||||
|
((3+4j), (3-4j))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if a == 0:
|
if a == 0:
|
||||||
raise ValueError("Coefficient 'a' must not be zero for quadratic equations.")
|
raise ValueError("Coefficient 'a' must not be zero.")
|
||||||
delta = b * b - 4 * a * c
|
delta = b * b - 4 * a * c
|
||||||
if delta >= 0:
|
|
||||||
return str((-b + sqrt(delta)) / (2 * a)), str((-b - sqrt(delta)) / (2 * a))
|
root_1 = (-b + sqrt(delta)) / (2 * a)
|
||||||
"""
|
root_2 = (-b - sqrt(delta)) / (2 * a)
|
||||||
Treats cases of Complexes Solutions(i = imaginary unit)
|
|
||||||
Ex.: a = 5, b = 2, c = 1
|
return (
|
||||||
Solution1 = (- 2 + 4.0 *i)/2 and Solution2 = (- 2 + 4.0 *i)/ 10
|
root_1.real if not root_1.imag else root_1,
|
||||||
"""
|
root_2.real if not root_2.imag else root_2,
|
||||||
snd = sqrt(-delta)
|
)
|
||||||
if b == 0:
|
|
||||||
return f"({snd} * i) / 2", f"({snd} * i) / {2 * a}"
|
|
||||||
b = -abs(b)
|
|
||||||
return f"({b}+{snd} * i) / 2", f"({b}+{snd} * i) / {2 * a}"
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
solutions = QuadraticEquation(a=5, b=6, c=1)
|
solutions = quadratic_roots(a=5, b=6, c=1)
|
||||||
print("The equation solutions are: {} and {}".format(*solutions))
|
print("The solutions are: {} and {}".format(*solutions))
|
||||||
# The equation solutions are: -0.2 and -1.0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
Loading…
x
Reference in New Issue
Block a user