SDDSlib
Loading...
Searching...
No Matches
SDDS
mdbmth
zeroNewton.c
Go to the documentation of this file.
1
/**
2
* @file zeroNewton.c
3
* @brief Implements the zeroNewton function for finding zeros of a function using Newton's method with numerical derivatives.
4
*
5
* @copyright
6
* - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7
* - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8
*
9
* @license
10
* This file is distributed under the terms of the Software License Agreement
11
* found in the file LICENSE included with this distribution.
12
*
13
* @author M. Borland, C. Saunders, R. Soliday
14
*/
15
16
#include "mdb.h"
17
18
/**
19
* @brief Finds the zero of a function using Newton's method with numerical derivative computation.
20
*
21
* This function attempts to find a value `x` such that `fn(x)` is approximately equal to the given `value`.
22
* It employs Newton's iterative method, where the derivative is estimated numerically using finite differences.
23
*
24
* @param fn Pointer to the function for which the zero is to be found.
25
* @param value The target value to solve for, i.e., find `x` such that `fn(x) = value`.
26
* @param x_i Initial guess for the independent variable.
27
* @param dx Increment used for numerical derivative computation.
28
* @param n_passes Number of iterations to perform.
29
* @param _zero Acceptable tolerance for the zero, determining when to stop the iterations.
30
*
31
* @return The `x` value where `fn(x)` is approximately equal to `value`, or `DBL_MAX` if no zero is found within the iteration limit.
32
*/
33
double
zeroNewton
(
34
double
(*fn)(),
/* pointer to function to be zeroed */
35
double
value,
/* value of function to find */
36
double
x_i,
/* initial value for independent variable */
37
double
dx,
/* increment for taking numerical derivatives */
38
long
n_passes,
/* number of times to iterate */
39
double
_zero
/* value acceptably close to true zero */
40
) {
41
double
f1, f2;
42
double
x1, x2;
43
double
dfdx;
44
long
i;
45
46
x1 = x2 = x_i;
47
for
(i = 0; i < n_passes; i++) {
48
if
(fabs(f1 = (*fn)(x1)-value) < _zero)
49
return
(x1);
50
if
(i == n_passes - 1)
51
return
((x1 + x2) / 2);
52
f2 = (*fn)(x2 = x1 + dx) - value;
53
dfdx = ((f2 - f1) / dx);
54
x1 += -f1 / dfdx;
55
}
56
return
(DBL_MAX);
/* shouldn't happen */
57
}
zeroNewton
double zeroNewton(double(*fn)(), double value, double x_i, double dx, long n_passes, double _zero)
Finds the zero of a function using Newton's method with numerical derivative computation.
Definition
zeroNewton.c:33
Generated by
1.12.0