python - 使用递归求函数的导数(三点端点公式)
问题描述
我需要使用三点端点公式从函数中找到 n 导数。
谁能帮我写代码?因为我的似乎真的很缺乏。
这是我的代码:
formula = input('Input the formula here : ')
n = input('Input the exponent here: ')
def f(x):
return eval(formula)
fungsi = pow(formula,n)
x0 = eval(input('Input the approximation of x here : '))
h = eval(input('Input the stepsize h here : '))
def TPEP(x,h,n,formula): #Three Point End Point
return (1/(2*h))*(-3*f(x,n-1)+4*f(x+h,n-1)-f(x+2*h,n-1))
print('Derivative of f in x0 = {0} is : '.format(x0))
print("f'({0}) = {1:.7f} (Three Point Endpoint)".format(x0,TPEP(x0,h,n,formula)))
如果有人可以提供帮助,我将不胜感激。谢谢你。
解决方案
我认为主要的一点是你必须检查你的TPEP
. 第二件事是您实际上必须执行递归:您正在调用f
,而不是导数的递归近似TPEP
。通过其他一些修复(小心,未经彻底测试且无错误处理):
import math
formula = input('Input the formula here : ')
n = int(input('Input the degree of derivative here: '))
def f(formula, x):
return eval(formula, globals(), {'x': x}) # use global and local scope
x0 = float(input('Input the approximation of x here : ')) # no error handling here - TODO
h = float(input('Input the stepsize h here : '))
def TPEP(x, h, n, formula): # Three Point End Point
if n <= 1: # need to check for iteration stop: the grade of derivatives
return (1/(2*h))*(-3*f(formula, x)+4*f(formula, x+h)-f(formula, x+2*h))
return (1/(2*h))*(-3*TPEP(x,h,n-1,formula)+4*TPEP(x+h,h,n-1,formula)-TPEP(x+2*h,h,n-1,formula)) # error-term omitted
print('Derivative of f in x0 = {0} is : '.format(x0))
print("f'({0}) = {1:.7f} (Three Point Endpoint)".format(x0, TPEP(x0, h, n, formula)))
产生
Input the formula here : x**3-3*x**2-1
Input the degree of derivative here: 2
Input the approximation of x here : 2
Input the stepsize h here : .1
Derivative of f in x0 = 2.0 is :
f'(2.0) = 6.0000000 (Three Point Endpoint)
同样在你eval
的 of 中f
,使用一个变量(这里是本地范围)在不同的值上方便地评估它x
。
推荐阅读
- amazon-s3 - 我想知道,如何通过指定一些分支从多分支编写 Jenkinsfile
- c# - 为什么等待之前的异常不会在没有等待的情况下抛出?
- python - 在有和没有特定条件的情况下循环遍历 Pandas DataFrame 中的 2 列
- javascript - 如何从 Redux/react 中的数组状态中删除对象
- javascript - 如何在 chrome 上查看我在亚马逊 as3 上上传的 zip 文件?
- express - 在没有提示的情况下登录用户
- python - 如何通过 Python 运行 C# 控制台应用程序?
- android - TransitionSet - Outgoing Activity 在不指定的情况下淡出
- c++ - 如何从 C/C++ 中的 MAC 地址获取供应商 OUI 和设备名称
- android - 在房间数据库中存储多个图像