/* Minimization by repetitive step reduction divides the initial interval
* into n segments. Repeats k times. Final resolution is n^-k
*/
double minimize(double (*f)(double), double x0, double x1, long n, int k){
static double xmin, ymin;
static double dx = (x1 - x0)/n;
double x, y;
for(int i=0; i<k; i++){
xmin = x0;
ymin = f(x0);
x = x0 + dx;
y = f(x);
while((x < x1) && (y <= ymin)){
ymin = y;
xmin = x;
x += dx;
y = f(x);
}
x0 = max(x0, x - 2*dx);
x1 = min(x1, x);
dx = dx/10;
}
return xmin;
}
|