1
0
Fork 0

Add: basic python quadratic equation solver

This commit is contained in:
Aroy-Art 2024-09-12 19:46:00 +02:00
parent 14ff02790c
commit c667ec9301
Signed by: Aroy
GPG key ID: DB9689E9391DD156

46
Python/pq.py Normal file
View file

@ -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)