python - 创建一个计算三阶导数的类
问题描述
我目前正在处理一项任务,我必须创建一个计算第三个导数的类。在这种情况下,第三个导数的公式如下:
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'
我怎样才能解决这个问题?
解决方案
你写f*(x - 2*h)
而不是f(x - 2*h)
. 我认为你第二次做对了。
推荐阅读
- javascript - ReactJs:是否可以检索此标签 {this.state.value} 标签内的编辑值
- javascript - Oauth facebook 登录后出现“无法访问”错误
- python - 在不使用类的情况下从 Python 中的另一个函数中调用一个函数
- heroku - 部署 mern 应用程序期间的 Heroku 错误
- csv - 在 Create React App 中导入 .csv 文件时出现“找不到模块”
- c# - 如何在 dbcontext.SqlQuery 查询中输入变量?
- docker - K8S iptables 与 Pod 内的容器之间的关系
- javascript - 我应该使用原型装饰器还是有其他方法?
- azure - 具有 SharePoint 连接的 Azure 逻辑应用
- apache - 如何在我的 htaccess 重写中使参数可选?