我如何创建或更改多项式系数

问题描述 投票:-1回答:1

我有此代码,我想对其进行编辑以执行其他操作:

def pol(poly, n, x):
    result = poly[0]

    #Using Horner's method
    for i in range(1, n):
       result = result * x + poly[i]

    return result
#Let us evaluate value of
#ax^3 - bx^2 - x - 10 for x = 1
poly = [5, 9, -1, -10]
x = 1
n = len(poly)

print("Value of polynomial is: ", pol(poly, n, x))

我想知道如何改变多项式的系数。这段代码只是计算:

x^3 and x^2

如何使该代码例如计算该多项式:

p(x) = 5x^10 + 9x - 7x - 10

或Python中的任何多项式?

python python-3.x function
1个回答
0
投票

您的代码永远不会提高x的作用-您需要解决这个问题-您也可以在函数内移动len(poly)

def pol(poly, x):
    n = len(poly)

    rp = poly[::-1]  # [-10, -1, 9, 5] so they correlate with range(n) as power

    print("Poly:",poly, "for x =",x) 
    result = 0
    for i in range(n):
        val = rp[i] * x**i
        print(rp[i],' * x^', i, ' = ', val, sep='')  # debug output
        result += val

    return result

# 5x^3 + 9x^2 - x - 10 for x = 1
poly = [5, 9, -1, -10]
x = 2  # 1 is a bad test candidate - no differences for 1**10 vs 1**2
n = len(poly)

print("Value of polynomial is: ", pol(poly, x))

输出:

Poly: [5, 9, -1, -10] for x = 2
-10 * x^0 = -10
-1 * x^1 = -2
9 * x^2 = 36
5 * x^3 = 40
Value of polynomial is:  64
© www.soinside.com 2019 - 2024. All rights reserved.