0

I am trying to implement the Newton-Raphson method using a single function pointer. The function must contain both the equation and its derivative. I am having difficulty passing through these two separate functions within the test function.

#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;

}

Thank you

Robert Penfield
  • 15
  • 1
  • 1
  • 5

1 Answers1

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

}
Rohan
  • 52,392
  • 12
  • 90
  • 87
  • When actually using the test_function, how do I show that I want to use function *f alone rather than function *f_prime, and vice versa - since we're taking in 3 parameters? – Robert Penfield Nov 11 '13 at 19:00
  • This removed many of the issues, thank you. For some reason, I still get a "f undeclared in NC" and "f_prime undeclared in NC" warning. Are they not passed properly in my function? – Robert Penfield Nov 11 '13 at 19:16
  • @RobertPenfield, yes, `f` and `f_prime` are not parameters of `NR` function so you need to define them in `NR`. See updated answer again. – Rohan Nov 11 '13 at 19:21
  • @RobertPenfield, accept it as answer if it solves your query. – Rohan Nov 11 '13 at 19:57