3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
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.
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.
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.
21 #include <gsl/gsl_multiroots.h>
24 gsl_multiroot_fdjacobian (gsl_multiroot_function * F,
25 const gsl_vector * x, const gsl_vector * f,
26 double epsrel, gsl_matrix * jacobian)
28 const size_t n = x->size;
29 const size_t m = f->size;
30 const size_t n1 = jacobian->size1;
31 const size_t n2 = jacobian->size2;
34 if (m != n1 || n != n2)
36 GSL_ERROR ("function and jacobian are not conformant", GSL_EBADLEN);
43 x1 = gsl_vector_alloc (n);
47 GSL_ERROR ("failed to allocate space for x1 workspace", GSL_ENOMEM);
50 f1 = gsl_vector_alloc (m);
56 GSL_ERROR ("failed to allocate space for f1 workspace", GSL_ENOMEM);
59 gsl_vector_memcpy (x1, x); /* copy x into x1 */
61 for (j = 0; j < n; j++)
63 double xj = gsl_vector_get (x, j);
64 double dx = epsrel * fabs (xj);
71 gsl_vector_set (x1, j, xj + dx);
74 int f_stat = GSL_MULTIROOT_FN_EVAL (F, x1, f1);
76 if (f_stat != GSL_SUCCESS)
78 status = GSL_EBADFUNC;
79 break; /* n.b. avoid memory leak for x1,f1 */
83 gsl_vector_set (x1, j, xj);
85 for (i = 0; i < m; i++)
87 double g1 = gsl_vector_get (f1, i);
88 double g0 = gsl_vector_get (f, i);
89 gsl_matrix_set (jacobian, i, j, (g1 - g0) / dx);
93 gsl_vector_view col = gsl_matrix_column (jacobian, j);
94 int null_col = gsl_vector_isnull (&col.vector);
95 /* if column is null, return an error - this may be due to
96 dx being too small. Try increasing epsrel */
103 gsl_vector_free (x1);
104 gsl_vector_free (f1);