gsl_multimin__diff.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* multimin/diff.c
  2. *
  3. * Copyright (C) 2000 David Morrison
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. */
  19. #include "gsl__config.h"
  20. #include "gsl_multimin.h"
  21. int
  22. gsl_multimin_diff (const gsl_multimin_function * f,
  23. const gsl_vector * x, gsl_vector * g)
  24. {
  25. size_t i, n = f->n;
  26. double h = GSL_SQRT_DBL_EPSILON;
  27. gsl_vector * x1 = gsl_vector_alloc (n); /* FIXME: pass as argument */
  28. gsl_vector_memcpy (x1, x);
  29. for (i = 0; i < n; i++)
  30. {
  31. double fl, fh;
  32. double xi = gsl_vector_get (x, i);
  33. double dx = fabs(xi) * h;
  34. if (dx == 0.0) dx = h;
  35. gsl_vector_set (x1, i, xi + dx);
  36. fh = GSL_MULTIMIN_FN_EVAL(f, x1);
  37. gsl_vector_set (x1, i, xi - dx);
  38. fl = GSL_MULTIMIN_FN_EVAL(f, x1);
  39. gsl_vector_set (x1, i, xi);
  40. gsl_vector_set (g, i, (fh - fl) / (2.0 * dx));
  41. }
  42. gsl_vector_free (x1);
  43. return GSL_SUCCESS;
  44. }