【发布时间】:2021-02-06 04:26:28
【问题描述】:
我目前正在处理一项任务,我必须创建一个计算第三个导数的类。在这种情况下,第三个导数的公式如下:
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'
我该如何解决这个问题?
【问题讨论】:
标签: python list loops class plot