查找导数时,在python 3中,如何使用filter函数仅返回导数未乘以零的项?

时间:2018-10-25 15:27:45

标签: python derivative

我写了一个函数,给定一个方程的项,就可以找到导数。但是,当一项为零时,函数会崩溃。我将如何使用过滤器确保乘以零的项不返回?

这是我的基准代码,可以正常工作,但尚不包含过滤器:

def find_derivative(function_terms):
    return [(function_terms[0][0]*function_terms[0][1], function_terms[0][1]-1),(function_terms[1][0]*function_terms[1][1], function_terms[1][1]-1)]

function_terms [1] [1] -1将导数项的幂减少1。

它是这样的。

输入:

# Represent each polynomial term with a tuple of (coefficient, power)

# f(x) = 4 x^3 - 3 x
four_x_cubed_minus_three_x = [(4, 3), (-3, 1)]
find_derivative(four_x_cubed_minus_three_x)  

输出:

[(12, 2), (-3, 0)]

这是12 x^2 - 3

的正确答案

但是在这里它崩溃了:

输入:

# f(x) = 3 x^2 - 11
three_x_squared_minus_eleven = [(3, 2), (-11, 0)]                       
find_derivative(three_x_squared_minus_eleven) 

在给定方程的情况下,应该找到导数。

输出:

((6, 1), (0, -1))

这是0 * x^(-1)的“幽灵”术语;我不希望打印这个术语。

预期输出:     [(6,1)]

3 个答案:

答案 0 :(得分:0)

您可以使用filter()函数来过滤元组列表,然后在过滤后的列表上应用逻辑。这样的事情应该起作用。

filtered_terms = list(filter(lambda x: x[1]!=0, function_terms))

现在,您有没有常量的元组。因此,与其对硬导数进行硬编码,不如遍历列表以获得导数。

result = []
for term in filtered_terms:
    result.append((term[0]*term[1], term[1]-1))
return result

答案 1 :(得分:0)

Python中有一个名为sympy的符号数学求解器。也许对您有用。

from sympy import *
x = symbols('x')
init_printing(use_unicode=True)

equation = 4*x**3 -3*x
diff_equation = equation.diff()
solution = diff_equation.subs({x:2})

答案 2 :(得分:0)

两项更改:

  1. 让您的例程遍历多项式项,一次处理一次,而不是完全依赖于两个项。
  2. 在遇到单个术语时将其应用到过滤器中。

我将其扩展为还消除了零系数和零指数的任何事物。由于符号微分定理同样适用,所以我添加了一个带有负指数的测试用例。

def find_derivative(function_terms):
    return [(term[0]*term[1], term[1]-1)
            for i, term in enumerate(function_terms)
                   if term[0] * term[1] != 0 ]

four_x_cubed_minus_three_x = [(4, 3), (-3, 1)]
print(find_derivative(four_x_cubed_minus_three_x) )

three_x_squared_minus_eleven = [(3, 2), (-11, 0)]
print(find_derivative(three_x_squared_minus_eleven) )

fifth_degree = [(1, 5), (-1, 4), (0, 3), (8, 2), (-16, 0), (1, -2)]
print(find_derivative(fifth_degree) )

输出:

[(12, 2), (-3, 0)]
[(6, 1)]
[(5, 4), (-4, 3), (16, 1), (-2, -3)]