Решатель квадратных уравнений в Python: методы и примеры кода

Вот несколько методов решения квадратного уравнения с использованием Python, а также примеры кода:

  1. Использование квадратичной формулы:

    import cmath
    def solve_quadratic_formula(a, b, c):
    # Calculate the discriminant
    discriminant = cmath.sqrt(b2 - 4*a*c)
    # Compute the solutions using the quadratic formula
    x1 = (-b + discriminant) / (2*a)
    x2 = (-b - discriminant) / (2*a)
    return x1, x2
    # Example usage
    a = 1
    b = -3
    c = 2
    x1, x2 = solve_quadratic_formula(a, b, c)
    print("Solution 1:", x1)
    print("Solution 2:", x2)
  2. Использование метода факторизации:

    def solve_by_factorization(a, b, c):
    # Factorize the quadratic equation
    factors = (a, b, c)
    for i in range(2, abs(c) + 1):
        if c % i == 0:
            factors = (factors[0] / i, factors[1] / i, factors[2] / i)
    # Extract the solutions from the factors
    x1 = -factors[0] / factors[2]
    x2 = -factors[1] / factors[2]
    return x1, x2
    # Example usage
    a = 1
    b = -3
    c = 2
    x1, x2 = solve_by_factorization(a, b, c)
    print("Solution 1:", x1)
    print("Solution 2:", x2)
  3. Использование библиотеки NumPy:

    import numpy as np
    def solve_with_numpy(a, b, c):
    # Create an array of coefficients
    coefficients = np.array([a, b, c])
    # Use the roots() function from NumPy to calculate the solutions
    solutions = np.roots(coefficients)
    return solutions
    # Example usage
    a = 1
    b = -3
    c = 2
    solutions = solve_with_numpy(a, b, c)
    print("Solutions:", solutions)