From c667ec9301aaed2af26f5c322180edf42e1e5a3b Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Thu, 12 Sep 2024 19:46:00 +0200 Subject: [PATCH] Add: basic python quadratic equation solver --- Python/pq.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/pq.py diff --git a/Python/pq.py b/Python/pq.py new file mode 100644 index 0000000..a53b8b2 --- /dev/null +++ b/Python/pq.py @@ -0,0 +1,46 @@ +import math + + +def solve_pq(p, q): + print(f"Solving the quadratic equation: x^2 + ({p})x + ({q}) = 0") + + # Step 1: Calculate p/2 + p_half = p / 2 + print(f"Step 1: Calculate p/2 -> p/2 = {p_half}") + + # Step 2: Calculate (p/2)^2 + p_half_squared = p_half**2 + print(f"Step 2: Calculate (p/2)^2 -> ({p_half})^2 = {p_half_squared}") + + # Step 3: Calculate discriminant (p/2)^2 - q + discriminant = p_half_squared - q + print( + f"Step 3: Calculate the discriminant -> ({p_half_squared}) - ({q}) = {discriminant}" + ) + + # Step 4: Check if discriminant is non-negative (real solutions exist) + if discriminant < 0: + print("Step 4: Discriminant is negative, no real solutions.") + return + + # Step 5: Calculate the square root of the discriminant + sqrt_discriminant = math.sqrt(discriminant) + print( + f"Step 5: Calculate the square root of the discriminant -> sqrt({discriminant}) = {sqrt_discriminant}" + ) + + # Step 6: Calculate the two possible solutions + x1 = -p_half + sqrt_discriminant + x2 = -p_half - sqrt_discriminant + print("Step 6: Calculate the two solutions:") + print(f"x1 = -({p_half}) + {sqrt_discriminant} = {x1}") + print(f"x2 = -({p_half}) - {sqrt_discriminant} = {x2}") + + # Step 7: Output the solutions + print(f"Solutions: x1 = {x1}, x2 = {x2}") + + +# Example usage +p = float(input("Enter the value of p: ")) +q = float(input("Enter the value of q: ")) +solve_pq(p, q)