首页 > 解决方案 > 使用递归求函数的导数(三点端点公式)

问题描述

我需要使用三点端点公式从函数中找到 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)))

如果有人可以提供帮助,我将不胜感激。谢谢你。

标签: pythonrecursionderivative

解决方案


我认为主要的一点是你必须检查你的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


推荐阅读