Matteo's Coding Project
Coding ProjectMatteo
plain_text
9 months ago
2.9 kB
15
Indexable
# Quadratic Equation Solver with Analysis
# This program solves quadratic equations of the form ax^2 + bx + c = 0,
# analyzes their roots, and provides additional insights.
# Function to validate user input for numeric values
def validate_input(prompt):
"""
Validates user input to ensure it is a numeric value.
Re-prompts the user until valid input is provided.
"""
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a numeric value.")
# Function to calculate roots of a quadratic equation
def calculate_roots(a, b, c):
"""
Uses the quadratic formula to calculate the roots of the equation ax^2 + bx + c = 0.
Handles edge cases such as zero or negative discriminants.
"""
discriminant = b**2 - 4*a*c # Calculate the discriminant
print(f"\nDiscriminant (b^2 - 4ac): {discriminant}")
# Analyze the discriminant to determine the nature of the roots
if discriminant > 0:
# Two distinct real roots
root1 = (-b + discriminant**0.5) / (2*a)
root2 = (-b - discriminant**0.5) / (2*a)
return f"Two real roots: {root1:.2f} and {root2:.2f}"
elif discriminant == 0:
# One repeated real root
root = -b / (2*a)
return f"One real root: {root:.2f}"
else:
# Complex roots
real_part = -b / (2*a)
imaginary_part = abs(discriminant)**0.5 / (2*a)
return f"Two complex roots: {real_part:.2f} ± {imaginary_part:.2f}i"
# Function to analyze the equation at various x-values
def analyze_equation(a, b, c, start=-5, end=5):
"""
Analyzes the behavior of the quadratic equation at various x-values.
"""
print("\nAnalysis of the equation ax^2 + bx + c at various x-values:")
for x in range(start, end + 1):
y = a*x**2 + b*x + c
print(f"At x = {x}, y = {y:.2f}")
# Main function to interact with the user and run the program
def main():
"""
Main program that gathers input, solves the quadratic equation,
and analyzes its behavior at various x-values.
"""
print("Welcome to the Quadratic Equation Solver!")
print("The equation is in the form ax^2 + bx + c = 0.")
# Input validation for coefficients a, b, and c
a = validate_input("Enter the coefficient a (non-zero): ")
while a == 0: # Ensure 'a' is not zero
print("Coefficient 'a' cannot be zero for a quadratic equation.")
a = validate_input("Please enter a non-zero value for a: ")
b = validate_input("Enter the coefficient b: ")
c = validate_input("Enter the coefficient c: ")
# Calculate and display the roots
print("\nRoots of the equation:")
print(calculate_roots(a, b, c))
# Analyze the equation
analyze_equation(a, b, c)
# Run the program
if __name__ == "__main__":
main()Editor is loading...
Leave a Comment