0

我正在尝试使用单个函数指针来实现 Newton-Raphson 方法。该函数必须同时包含方程及其导数。我很难在测试函数中通过这两个单独的函数。

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>

double NR(double, double(*)(double, double*), double);

void test_function( double x, double * f, double * f_prime )
{
  *f = (x-2) * (x-2);
    *f_prime = 2*x - 4;
}

double NR( double x0, double (*test_function)(double x, double *f, double *f_prime), double precision )
{
  int i;
    while(!isnan(x0)){
      i = x0;
      x0 = (x0 - (test_function(x0, f, 0)/test_function(x0, 0, f_prime)));
      if(!isnan(x0))
    printf("%f\n",x0);
      if ( i - x0 < 0 )
    printf("NO ROOT FOUND");
      return -1;
      else if ( i - x0 > 0 && i - x0 < precision )
    break;
    }

}


int main(void)
{
  double x0 = 300;
  double precision = .0000001;

  double root = NR( x0, test_function, precision);

  printf("%f\n",root);

  return 0;

}

谢谢

4

1 回答 1

0

Update declaration of NR to take function pointer that takes 3 parameters as

double NR(double, double(*)(double, double*, double *), double);

instead of

double NR(double, double(*)(double, double*), double);

As you are passing 0 (or NULL) to either prime or f_prime, you can update test function as

void test_function( double x, double * f, double * f_prime )
{
    if(f)
      *f = (x-2) * (x-2);
    if(f_prime)
      *f_prime = 2*x - 4;
}

Also you need to update NR as below to define f and f_prime

double NR( double x0, double (*test_function)(double x, double *f, double *f_prime), double precision )
{
  int i;
  double f, f_prime;
  ...
  //your code
  ...
  //----------------------------v pass address -------------v
  x0 = (x0 - (test_function(x0, &f, 0)/test_function(x0, 0, &f_prime)));
  ....
  //your code

}
于 2013-11-11T18:55:07.517 回答