使用递归查找函数的导数(三点端点公式)

2024-09-23 22:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用三点端点公式求函数的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,h,n,formula)))

如果有人能帮忙,我将非常感激。多谢各位


Tags: ofthe代码inputreturnhereisdef
1条回答
网友
1楼 · 发布于 2024-09-23 22:19:53

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

同样,在feval中,使用一个变量(这里是局部范围)以不同的x-值方便地对其求值

相关问题 更多 >