Coding Project

 avatar
unknown
plain_text
a month ago
2.7 kB
4
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"

# 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
    result = calculate_roots(a, b, c)
    print("\nResult:", result)

    # Additional feature: Analyzing the equation at multiple x-values
    print("\nAnalysis of the equation ax^2 + bx + c at various x-values:")
    for x in range(-5, 6):  # Loop through x-values from -5 to 5
        y = a*x**2 + b*x + c
        print(f"At x = {x}, y = {y:.2f}")

# Run the program
if __name__ == "__main__":
    main()
Leave a Comment