Квадратичная формула находит значение для x1 и x2 по уравнению

Учитывая вложенный список l, содержащий значения коэффициентов, я пытаюсь вычислить квадратичную формулу, чтобы найти нули x, обозначенные как x1,x2. У меня есть цикл for, который проходит через этот список и дает мне значение для a, b и c из вложенного списка:

import math as m
l = [[1,2,1],[9,12,4],[1,-7,0],[1,2,-3]]#nested list
for x in l:
  q = x[1]*x[1]-4*x[0]*x[2] #b*b - 4*a*c
  q_sr = m.sqrt(q)#root of q
  x1 = (-x[1] + q_sr)/(2*x[0])#[1]=b and [0]=a
  x2 = (-x[1] - q_sr)/(2*x[0])#[1]=b and [0]=a
  eq = x[0]**2 + 2*x[1] + 1*x[2] #equation that im trying to get the x1 and x2

  print("a verdier: ", x[0])
  print("b verdier: ", x[1])
  print("c verdier: ", x[2])
  print("x1 verdier: ", x1)
  print("x2 verdier: ", x2) 

Здесь x[0],x[1] и x[2] — соответствующие позиции в списке l, например, 0 = a, 1 = b и 2 = c. Все это работает, и я получаю правильные значения для x1 и x2.

У меня возникли проблемы с вычислением нулей (x1, x2). Как рассчитать эти значения?


person user3768971    schedule 09.02.2016    source источник
comment
Исправьте отступ, если не возражаете.   -  person Goodies    schedule 09.02.2016
comment
l не лучшее имя для переменной, так как оно выглядит как 1   -  person Peter Wood    schedule 09.02.2016
comment
Возможный дубликат решателя квадратных уравнений не работает   -  person Barmar    schedule 09.02.2016


Ответы (2)


Сложный математический модуль отлично подходит для таких вещей.

import cmath
def quadratic(a, b, c):
    d = float(b**2 - 4*a*c)
    x1 = ((-b)-cmath.sqrt(d))/(2*a)
    x2 = ((-b)+cmath.sqrt(d))/(2*a)
    return [x.real if (x.imag == 0.0) else x for x in [x1, x2]]

Ради забавы

class Quadratic:
    def __init__(self, a, b, c):
        self.a, self.b, self.c = a, b, c
        self.d = float(self.b ** 2 - 4*self.a*self.c)
        self.x1 = ((-b)-cmath.sqrt(self.d))/(2*a)
        self.x2 = ((-b)+cmath.sqrt(self.d))/(2*a)

    @property
    def solution(self):
        return [x.real if x.imag == 0.0 else x for x in [self.x1, self.x2]]

    def __str__(self):
        return "X1 = {}, X2 = {}".format(*self.solution)


myList = [[1, 2, 1], [9, 12, 4], [1, -7, 0], [1, 2, -3]]
for _ in myList:
    print Quadratic(*_)
person Goodies    schedule 09.02.2016

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

from math import sqrt

coef_list = [[1,2,1],[9,12,4],[1,-7,0],[1,2,-3]]

# This following "for loop" will compute solutions x1 and x2 
# for any quadratic equation summarized in your coef_list. In your
# coef_list you have the following equations:
# y(x) = 1*x^2 + 2*x + 1
# y(x) = 9*x^2 + 12*x + 4
# ...
# y(x) = 1*x^2 + 2*x -3

for coef in coef_list:
    a, b, c = coef   # extract a, b and c from the inner lists
    q = b**2 - 4*a*c

    # In case q > 0 you have two solutions
    if q > 0:
        q_sqrt = sqrt(q)
        x1 = (-b + q_sqrt)/(2*a)#[1]=b and [0]=a
        x2 = (-b - q_sqrt)/(2*a)#[1]=b and [0]=a

    # In case q = 0 you have only one solution
    elif q == 0:
        x1 = -b/(2*a)
        x2 = x1

    # In case q < 0 you have no real solution
    else:
        raise ValueError("q is negative.")

    # print at all iteration of the loop to have solutions for every
    # equation in given in coef_list
    print "x1 = ", x1
    print "x2 = ", x2
    print "a = ", a, ", b = ", b, "and c = ",c
    print "-----"


# You don't need the next line since the equation you are trying to solve is 
# is defined in coef_list at line 0 (i.e. coef_list[0])     

#eq = x[0]**2 + 2*x[1] + 1*x[2] #equation that im trying to get the x1 and x2
person Roger Hache    schedule 09.02.2016