繁体   English   中英

导数 function python

[英]Derivative function python

我需要编写代码来推导 function 而不使用 NumPy 或 SymPy。 用户应输入 function 作为多项式(例如:2*x^3+5)和一个数字。 代码应编写 function 的第 n 次推导(函数 3*x^3 和数字 2(第二次推导):18*x^1)。 我有一些代码,但我有问题:如果 function 输入为 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 的差异,我通常不会像 go 我将提供一些解释作为代码中的注释。 一些假设:只允许多项式。 不允许使用科学记数法。 您的变量用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 

希望这可以帮助。

暂无
暂无

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

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