简体   繁体   English

计算多项式系数

[英]Evaluating Polynomial coefficients

I'm trying to write a function that takes as input a list of coefficients (a0, a1, a2, a3.....an) of a polynomial p(x) and the value x.我正在尝试编写一个函数,该函数将多项式 p(x) 的系数列表 (a0, a1, a2, a3.....an) 和值 x 作为输入。 The function will return p(x), which is the value of the polynomial when evaluated at x.该函数将返回 p(x),它是多项式在 x 处求值时的值。

A polynomial of degree n with coefficient a0, a1, a2, a3........an is the function系数为 a0, a1, a2, a3........an 的 n 次多项式是函数

p(x)= a0+a1*x+a2*x^2+a3*x^3+.....+an*x^n

So I'm not sure how to attack the problem.所以我不确定如何解决这个问题。 I'm thinking that I will need a range but how can I make it so that it can handle any numerical input for x?我在想我需要一个范围,但我怎样才能使它可以处理 x 的任何数字输入? I'm not expecting you guys to give the answer, I'm just in need of a little kick start.我不指望你们给出答案,我只是需要一点点开始。 Do I need a for loop, while loop or could recursive be an option here?我是否需要 for 循环、while 循环或递归在这里可以选择?

def poly(lst, x)

I need to iterate over the items in the list, do I use the indices for that, but how can I make it iterate over an unknown number of items?我需要迭代列表中的项目,我是否使用索引,但如何让它迭代未知数量的项目?

I'm thinking I can use recursion here:我想我可以在这里使用递归:

    def poly(lst, x):
        n = len(lst)
        If n==4:
           return lst[o]+lst[1]*x+lst[2]*x**2+lst[3]*x**3
        elif n==3:
           return lst[o]+lst[1]*x+lst[2]*x**2
        elif n==2:
           return lst[o]+lst[1]*x
        elif n==1:
           return lst[o]
        else:
            return lst[o]+lst[1]*x+lst[2]*x**2+lst[3]*x**3+lst[n]*x**n

This works for n<=4 but I get a index error: list index out of range for n>4, can't see why though.这适用于 n<=4,但我收到一个索引错误:列出 n>4 的索引超出范围,但不明白为什么。

The most efficient way is to evaluate the polynomial backwards using Horner's Rule.最有效的方法是使用霍纳规则向后评估多项式。 Very easy to do in Python:在 Python 中很容易做到:

# Evaluate a polynomial in reverse order using Horner's Rule,
# for example: a3*x^3+a2*x^2+a1*x+a0 = ((a3*x+a2)x+a1)x+a0
def poly(lst, x):
    total = 0
    for a in reversed(lst):
        total = total*x+a
    return total
def evalPoly(lst, x):
    total = 0
    for power, coeff in enumerate(lst): # starts at 0 by default
        total += (x**power) * coeff
    return total

Alternatively, you can use a list and then use sum :或者,您可以使用列表,然后使用sum

def evalPoly(lst, x):
        total = []
        for power, coeff in enumerate(lst):
            total.append((x**power) * coeff)
        return sum(total)

Without enumerate:不列举:

def evalPoly(lst, x):
    total, power = 0, 0
    for coeff in lst:
        total += (x**power) * coeff
        power += 1
    return total

Alternative to non-enumerate method:非枚举方法的替代方法:

def evalPoly(lst, x):
    total = 0
    for power in range(len(lst)):
        total += (x**power) * lst[power] # lst[power] is the coefficient
    return total

Also @DSM stated, you can put this together in a single line: @DSM 还指出,您可以将其放在一行中:

def evalPoly(lst, x):
    return sum((x**power) * coeff for power, coeff in enumerate(lst))

Or, using lambda :或者,使用lambda

evalPoly = lambda lst, x: sum((x**power) * coeff for power, coeff in enumerate(lst))

Recursive solution:递归解决方案:

def evalPoly(lst, x, power = 0):
    if power == len(lst): return (x**power) * lst[power]
    return ((x**power) * lst[power]) + evalPoly(lst, x, power + 1)

enumerate(iterable, start) is a generator expression (so it uses yield instead of return that yields a number and then an element of the iterable. The number is equivalent to the index of the element + start. enumerate(iterable, start)是一个生成器表达式(因此它使用yield而不是return产生一个数字,然后是一个可迭代的元素。该数字相当于元素的索引 + start。

From the Python docs, it is also the same as : 从 Python 文档来看,它也与以下内容相同

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

simple:简单的:

def poly(lst, x): 
  n, tmp = 0, 0
  for a in lst:
    tmp = tmp + (a * (x**n))
    n += 1

  return tmp

print poly([1,2,3], 2)

simple recursion:简单递归:

def poly(lst, x, i = 0):
  try:
    tmp = lst.pop(0)
  except IndexError:
    return 0
  return tmp * (x ** (i)) + poly(lst, x, i+1)

print poly([1,2,3], 2)

Either with recursion, or without, the essence of the solution is to create a loop on "n", because the polynomial starts at x^0 and goes up to a_n.x^n and that's the variable you should also consider as an input.无论有没有递归,解决方案的本质都是在“n”上创建一个循环,因为多项式从 x^0 开始并上升到 a_n.x^n,这是您也应该考虑作为输入的变量. Besides that, use a trick called multiply and accumulate to be able to calculate partial results on each loop iteration.除此之外,使用称为乘法和累加的技巧能够计算每次循环迭代的部分结果。

def evalPoly(lst, x, power):
    if power == 0:
        return lst[power]
    return ((x**power) * lst[power]) + evalPoly(lst, x, power - 1)

lst = [7, 1, 2, 3]
x = 5
print(evalPoly(lst, x, 3))

Equation to evaluate is - 3x^3 + 2x^2 + x + 7 when x = 5, result is - 437当 x = 5 时,要评估的方程为 - 3x^3 + 2x^2 + x + 7,结果为 - 437

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM