在Python中找到多项式的导数

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

我对此任务有疑问。我必须打印一个多项式,这是用户的输入。 (我也对此有疑问,因为它可以是任何程度的多项式,但我不确定如何打印它)。任务的第二部分是找到该多项式的导数。我试图通过向用户询问该多项式的阶数和系数,然后创建一个列表来实现此目的,但是我认为这不是一个好方法,因此请帮助我!

我有这样的事情:

n = int(input("What is a degree of poly: "))
lista = []
for i in range (n+1):
    a = int(input("What are the coefficients "))
    lista.append(a)

lista1 = []
b = n
d = 0
for k in range (n+1):
    c = int(lista[d])*int(b)
    lista1.append(c)
    b = b - 1
    d = d + 1

print(lista1)
python polynomial-math polynomials derivative
1个回答
0
投票

您将需要使用一个名为sympy的模块。您需要做的第一件事是pip install sympy。如果不起作用,请评论您正在使用的编辑器,我可能会提供帮助。

然后您可以运行此代码,该代码将在注释的帮助下进行自我解释,并经过我的测试。

import sympy as sp  # Import sympy

x = sp.Symbol('x')  # Makes a new symbol: x

degree = int(input("Degree of Polynomial"))  # get the degree of the polynomial

polynomial = 0  # Start with nothing in the polynomial and slowly add to it

for power in range(degree+1):  # degree + 1 is so that we loop it once more that number of degrees to get x^0 term
    coefficient = int(input(("What is the coefficient of the x^" + str(power) + " term")))
    # Get the coefficient of the term
    if coefficient != 0:  # we do not want to print 0*x^4 or something like that hence only add to the poly if not 0
        polynomial += coefficient*x**power  # coefficient*x^power: Pretty self explanatory

polynomialString = str(polynomial).replace('**', '^')  # Replace pythons symbol for power: ** with ^

print("Your Polynomial is", polynomialString)  # Print the polynomial

derivative = sp.diff(polynomial, x)  # Differentiate the polynomial
derivativeStr = str(derivative).replace('**', '^')  # derivative after replacing ** with ^ 

print("The derivative of ", polynomialString, " is ", derivativeStr)  # Prints the derivative

© www.soinside.com 2019 - 2024. All rights reserved.