派生函数python



我需要在不使用NumPy或SymPy的情况下编写函数派生代码。用户应将函数输入为多聚体(例如:2*x^3+5(和一个数字。代码应该写函数的第n个导数(函数3*x^3和数字2(二阶导数(:18*x^1(。我有一些代码,但我有问题:如果一个函数被输入为2*x^3+5*x,它只打印2*x^3的派生(或者派生,但在下一行-就像两个单独的函数一样(,并且它不显示第n个派生(但一些接近n的数字(。一些改进的想法?1

代码:

a=input("Polinom:")
b=int(input("Number:"))  
z=a.split("+")

i,j=0
while i<b:
for j in range(len(z)):
coeff=int(z[j][0])
exp=int(z[j][-1])
e=("{}x^{}".format(coeff*exp,exp-1))
print(e)
z.append(e)

coeff=coeff*exp
exp=exp-1
i+=1

请注意,这个答案是基于您现有的代码的,并简单地展示了如何在此基础上进行扩展以改进到目前为止的内容。这不是我通常在python中进行差异处理的方式。我将在代码中提供一些解释作为注释。几个假设:只允许使用多项式。不允许使用科学记数法。您的变量用x表示,并省略乘法符号。

import re
p = '2x^6-4x^5+3x^3' #example of polynomial
b = 3 #no of derivations
i=0
while i<=b:
z = re.split('(+|-)',p) #in your code you only check for +. - can also be present
z = list(filter(None, z)) #output of the last couple lines of code: ['2x^6', '-', '4x^5', '+', '3x^3']
deriv = '' #this is where we save the derivative expression
for j in range(len(z)):
if 'x' in z[j]: #only do something when we encounter a monome
sign = ''
if j!=len(z) - 1 and 'x' in z[j+2]: #we add the sign only if we are not at the end of  the list and if the next monome will not vanish during differentiation
sign = z[j+1]
coeff=int(z[j].split('x')[0]) #get coefficient
exp = z[j].split('^') #split monome to get exponent
if len(exp)>1:
e = int(exp[1])
if e - 1 > 1:
deriv+=("{}x^{}{}".format(coeff*e,e-1,sign)) if sign != '' else ("{}x^{}".format(coeff*e,e-1))
else: #if x is of power 2, it will be shown as x and x^1
deriv+=("{}x{}".format(coeff*e, sign)) if sign != '' else ("{}x".format(coeff*e))
else: #if x is of the power of 1, x will not be shown in the expression
deriv+=("{}{}".format(coeff,sign)) if sign != '' else ("{}".format(coeff))
print(deriv) #print the current derivative
p = deriv    #current derivative becomes the next polynomial to differentiate 
i+=1 

希望这能有所帮助。

最新更新