首页 > 解决方案 > 创建一个计算三阶导数的类

问题描述

我目前正在处理一项任务,我必须创建一个计算第三个导数的类。在这种情况下,第三个导数的公式如下:

https://gyazo.com/cc4d6d9bb152c6f6583179ad4ffab09d

要测试该类,我必须使用该函数:

f(x) = cos (x)

这个函数的第三个导数应该是:

f'''(x) = sin(x)

这是我正在处理的代码:

from math import *
def f(x):
    return cos(x)

class Third_derivate:
    def __init__ (self, f, h):
        self.f = f
        self.h = h
        
    def __call__ (self, x):
        
        f = self.f
        h = self.h
        
        return (- 0.5 *f*(x - 2*h) + f(x - h) - f(x - h)  + 0.5 * f(x + 2*h)) / h**3
    
def test():
    f = lambda x: a*x + b
    a = 5
    b = 10
    dfdx = Third_derivate(f, h = 0.5)
    diff = abs(dfdx(4.5) - a)
    assert diff < 1E-14, 'class has a fault, diff = %s' % diff
    
df = Third_derivate(cos, 1E-7)
x = 1
print(df(x))

我得到的错误代码是:

 return (- 0.5 *f*(x - 2*h) + f(x - h) - f(x - h)  + 0.5 * f(x + 2*h)) / h**3

TypeError: unsupported operand type(s) for *: 'float' and 'builtin_function_or_method'

我怎样才能解决这个问题?

标签: pythonlistloopsclassplot

解决方案


你写f*(x - 2*h)而不是f(x - 2*h). 我认为你第二次做对了。


推荐阅读