我对编码很陌生,我一直在寻找在线帮助编写一个将使用黄金分割法(显然是GNU科学图书馆有的C代码)的不可能的时间,虽然我没有任何运气找到它)找到牛顿最小化方法失败的最小函数。
具体来说,我想输入一个x值作为起点,并让代码输出函数的最小值和最小值点的x坐标。我的函数是f(x)= x 20 。我也被允许一些错误(< 10 -3 )。
我甚至不知道从哪里开始,我一直在互联网上,并没有找到任何有用的东西。我会非常感谢一些帮助,我可以在哪里找到更多信息,或者我如何实现这种方法。
编辑:
这是我现在的代码:
#include <gsl/gsl_errno.h> /* Defines GSL_SUCCESS, etc. */
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
int minimize_convex(gsl_function *F,double a, double b, double *x_min, double tol)
{
int status;
double h = (b - a) * .0000001; /* Used to test slope at boundaries */
/* First deal with the special cases */
if (b - a < tol)
{
*x_min = b;
status = GSL_SUCCESS;
}
/* If the min is at a, then the derivative at a is >= 0. Test for
* this case. */
else if (GSL_FN_EVAL(F, a + h) - GSL_FN_EVAL(F, a) >= 0)
{
*x_min = a;
status = GSL_SUCCESS;
}
/* If the min is at b, then the derivative at b is >= 0. Test for
* this case. */
else if (GSL_FN_EVAL(F, b - h) - GSL_FN_EVAL(F, b) >= 0)
{
*x_min = b;
status = GSL_SUCCESS;
}
else
{
/* Choose x_guess so that it's value is less than either of the two
* endpoint values. Since we've got this far, we know that at least
* of of F(a + h) and F(b - h) has this property. */
double x_guess;
x_guess = (GSL_FN_EVAL(F, a + h) < GSL_FN_EVAL(F, b - h)) ?
a + h : b - h;
int iter = 0, max_iter = 200;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
T = gsl_min_fminimizer_goldensection;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, F, x_guess, a, b);
do
{
iter++;
status = gsl_min_fminimizer_iterate(s); /* perform iteration */
status =
gsl_min_test_interval(a, b, tol, 0.0); /* |a - b| < tol? */
a = gsl_min_fminimizer_x_lower(s);
b = gsl_min_fminimizer_x_upper(s);
if (status == GSL_SUCCESS)
{
*x_min = gsl_min_fminimizer_x_minimum(s); /* current est */
}
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_min_fminimizer_free(s);
}
return status;
}
double f(double x, void *params)
{
double *p = (double *) params;
return (x^(50)) + *p;
}
double C = 0.0;
int main (void)
{
double m = 0.0, result;
double a = -1.0, b = 1.0;
double epsilon = 0.001;
int exit_val;
gsl_function F;
F.function = &f;
F.params = &C;
exit_val = minimize_convex(&F, a, b, m, &result, epsilon);
printf("Minimizer: %g\n", result);
printf("Function value: %g\n", f(result, &C));
printf("%d\n", exit_val);
return 0;
}
我收到以下错误: try.c:69:14:错误:二进制文件的操作数无效 表达式('double'和'double') return(x ^(50))+ * p;
try.c:81:54:错误:函数的参数太多了 打电话,预计5,有6 exit_val = minimize_convex(&amp; F,a,b,m,&amp; result,epsilon);
有什么想法吗?
答案 0 :(得分:2)
gsl有一个通用的最小化器,可以使用多种方法来实现最小化。有关如何使用最小化器的说明,请参见documentation。您可以通过将方法显示为gsl_min_fminimizer_goldensection
来将其设置为黄金分割方法。