1
0
Fork 0
LangPlayground/Python/pq.py

46 lines
1.4 KiB
Python

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)