递归找到二阶导数 [英] Recursively find the second derivative

查看:120
本文介绍了递归找到二阶导数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用C编写一个程序,该程序查找f(x)的二阶导数的数值,其中x给出.当我使用函数查找一阶导数时,一切似乎都正常,但是递归二阶导数部分始终为我提供0.0.这是我的功能:

I'm attempting to write a program in C which finds the numeric value of the second derivative of f(x) where x is given. When I use my function to find the first derivative, everything seems to be working okay, but the recursive second derivative part always gives me 0.0. Here's my function:

double derivative(double (*f)(double), double x0, int order) {
    if(order == 1){
        const double delta = 1.0e-6;
        double x1 = x0-delta;
        double x2 = x0+delta;
        double y1 = f(x1);
        double y2 = f(x2);

        return (y2 - y1) / (x2 - x1);
    } else if(order == 2) {
        const double delta = 1.0e-6;
        double x1 = derivative(f, x0, 1)-delta;
        double x2 = derivative(f, x0, 1)+delta;
        double y1 = derivative(f, f(x1), 1)-delta;
        double y2 = derivative(f, f(x2), 1)+delta;

        return (y2 - y1) / (x2 - x1);
    } else {
        printf("order too high error \n");
        return 0;
    }
}

我理解为什么它不能按预期工作-在这里,我尝试通过基于函数f和f'(x)的值进行推导来找到f的二阶导数.但是我已经为此工作了几个小时,而且我无法提出合适的算法来做到这一点.

I understand why it doesn't work as intended -- here I attempt to find the second derivative of f by deriving based on the function f and the value of f'(x). But I've been working on this for hours, and I cannot come up with a proper algorithm to do this.

任何帮助将不胜感激.预先感谢!

Any help would be very appreciated. Thanks in advance!

推荐答案

我会这样实现:

double derivative(double (*f)(double), double x0, int order)
{
         const double delta = 1.0e-6;
         double x1 = x0 - delta;
         double x2 = x0 + delta;
         if (order == 1) {
                  double y1 = f(x1);
                  double y2 = f(x2);

                  return (y2 - y1) / (x2 - x1);
          } else {
                  double y1 = derivative(f, x1, order - 1);
                  double y2 = derivative(f, x2, order - 1);

                  return (y2 - y1) / (x2 - x1);
          }
 }

因为这样就不需要订单过高的错误".

Because then there is no need for a "order too high error".

这篇关于递归找到二阶导数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆