评估多项式系数 [英] Evaluating Polynomial coefficients

查看:130
本文介绍了评估多项式系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将多项式p(x)的系数列表(a0,a1,a2,a3 ...... a n)和值x作为输入。该函数将返回p(x),这是在x处计算的多项式的值。

I'm trying to write a function that takes as input a list of coefficients (a0, a1, a2, a3.....a n) of a polynomial p(x) and the value x. The function will return p(x), which is the value of the polynomial when evaluated at x.

具有系数a0,a1,a2,a3的n次多项式........一个是函数

A polynomial of degree n with coefficient a0, a1, a2, a3........an is the function

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

所以我不确定如何解决这个问题。我在想我需要一个范围,但我怎么能这样做才能处理x的任何数字输入?我不希望你们给出答案,我只是需要一点启动。我是否需要一个for循环,while循环或递归可以作为一个选项吗?

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? 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?

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

这适用于n< = 4但我收到索引错误:list index超出n> 4的范围,虽然看不出原因。

This works for n<=4 but I get a index error: list index out of range for n>4, can't see why though.

推荐答案

简单:


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)

简单递归:


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)

这篇关于评估多项式系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆