给定方程

时间:2016-02-09 16:26:30

标签: python formula equation quadratic

给定包含系数值的嵌套列表l,我试图计算二次公式以找到x的零,表示为x1,x2。我有一个循环遍历此列表并从嵌套列表中给出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)时遇到问题。我该如何计算这些值?

2 个答案:

答案 0 :(得分:1)

复杂的数学模块非常适合这样的事情。

std::string

为了好玩

#include <type_traits>

template<typename T>   // primary template
struct Releaser
{
  template<typename V>
    void release( V v ) { }
};
template<>  // explicit specialization for T = std::true_type
struct Releaser<std::true_type>
{
  template<typename V>
    void release( V v ) { delete[] v; }
};

template <class T>
class Example
{
  private:
    T data;
  public:
    Example(): data(T()) {}
    Example(T typeData): data(typeData) {}
    typedef typename std::is_pointer<T>::value_type isptr_type;
    ~Example() {
      Releaser< isptr_type >::release( data );
    }
};

答案 1 :(得分:-1)

以下是您的代码的修改和评论版本,可帮助您了解您的操作。

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