amirvahid
01-21-2009, 08:16 AM
Hi All,
I am trying to optimize a parameter by minimizing an objective function. I wonder if you could tell me which routine and which chapter can perform this job. Thanks
amirvahid
01-22-2009, 02:30 PM
I think I somehow know the answer based on Chapters 3,10,15 but I wonder if you could write a sample code for optimization of 2 parameters in a function. Define an objective function and minimize it and give the best value for those 2 parameters. Sounds to me simplex and Powel algorithms.
davekw7x
01-24-2009, 12:00 PM
...sample code for optimization of 2 parameters in a function...Powel...
//
// Illustration of use of Numerical Recipes Version 3 Powell class
// to minimize a function with two parameters
//
// davekw7x
//
#include "../code/nr3.h"
#include "../code/mins.h"
#include "../code/mins_ndim.h"
//
// Minimize the following function
//
// f(x,y) = (x-1)^2 + (y-2)^2 + 3
//
//
Doub func(VecDoub_I & x)
{
return (x[0]-1.0)*(x[0]-1.0) + (x[1]-2.0)*(x[1]-2.0) + 3.0;
}
int main()
{
Int n = 2; // Number of parameters in the function
Int i;
//
// In general, you might have a better idea for an initial guess, but
// here, I'll just use zero values for the parameters.
//
VecDoub pinit(n, 0.0); // Initial guess is (0, 0)
VecDoub pmin; // Vector to hold the result from Powell minimization
cout << scientific;
cout << "Initial guess: minimum value = " << setw(13) << func(pinit) << " at: ";
for (i = 0; i < pinit.size(); i++) {
cout << setw(13) << pinit[i] << " ";
}
cout << endl << endl;
//
// Feed the function to the constructor
//
Powell <Doub(VecDoub_I &)> powell(func);
// Perform the minimization
pmin = powell.minimize(pinit);
cout << "Number of Powell iterations = " << powell.iter << endl << endl;
cout << "After Powell, minimum value = ";
cout << setw(13) << powell.fret << " at: ";
for (i = 0; i < n; i++) {
cout << setw(13) << pmin[i] << " ";
}
cout << endl << endl;
//
// Of course I made up a function for which I know
// the exact answer.
//
cout << "Actual minimum is 3.0 at 1.0 2.0" << endl << endl;
return 0;
}
Output:
Initial guess: minimum value = 8.000000e+00 at: 0.000000e+00 0.000000e+00
Number of Powell iterations = 1
After Powell, minimum value = 3.000000e+00 at: 1.000000e+00 2.000000e+00
Actual minimum is 3.0 at 1.0 2.0
Regards,
Dave
amirvahid
01-29-2009, 02:52 PM
Thanks Dave. It was really helpful. I will ask further questions as I use different recipes in my programs.
Cordially,
Amir