frprmn usage question


bystander
05-10-2008, 07:24 PM
Hi. This is the first time I'm using NR routines so I'm not sure if I'm doing it right.

I want to use frprmn and I have a trivial test case, but it's not behaving like I expected. It searches for the minimum of a 2D parabola (z = (x-x0)^2 + (y-y0)^2) and the minimum should be at the vertex (x0, y0), but the result turned out otherwise.


#include <stdio.h>
#include "nr.h"

float X0 = 2.5;
float Y0 = 4.7;

float parabola(float p[])
{
return ( (p[0]-X0)*(p[0]-X0) + (p[1]-Y0)*(p[1]-Y0) );
}

void dparabola(float p[], float df[])
{
df[0] = 2*(p[0]-X0);
df[1] = 2*(p[1]-Y0);
}

int main(int argc, char* argv[])
{
int n = 2;

int iter;
float fret;
float p[] = { 0, 0 };
float ftol = 1.0e-5;

frprmn(p, n, ftol, &iter, &fret, &parabola, &dparabola);

printf("num itr = %d\n", iter);
printf("min at (x, y) = (%f, %f)\n", p[0], p[1]);
printf("the min = %f\n", fret);

return 0;
}


And the output turns out to be this. The y is right, but x is not.
num itr = 3
min at (x, y) = (0.000000, 4.700004)
the min = 20.250010

Can anyone tell me what I did wrong? Thanks a lot.

bystander
05-10-2008, 11:51 PM
I figured out the problem. NR vectors start at position 1, but I was used to starting arrays at position 0 (having been a systems student for the past few years). It makes sense that the routine is ignoring my p[0] but got p[1] right. Changing p to 3 elements and shifting the indices fixed it.