微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用递归求函数的导数三点端点公式

如何解决使用递归求函数的导数三点端点公式

我需要使用三点端点公式从函数中找到 n 导数。

This is the general formula

谁能帮我写代码?因为我的似乎真的缺乏。

这是我的代码

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,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,n-1,formula)+4*TPEP(x+h,formula)-TPEP(x+2*h,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,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)

同样在 evalf 中,使用变量(此处为局部作用域)在不同的 x 值下方便地对其进行评估。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。