Secant Method implementation.
More...
#include <assert.h>
#include <math.h>
#include <stdio.h>
|
#define | TOLERANCE 0.0001 |
| for assert
|
|
#define | NMAX 100 |
|
|
double | func (double x) |
| Continuous function for which we want to find the root.
|
|
double | secant_method (double x0, double x1, double tolerance) |
| Root-finding method for a continuous function given two points.
|
|
static void | test () |
| Self-test implementations.
|
|
int | main () |
| Main function.
|
|
Secant Method implementation.
Find a continuous function's root by using a succession of roots of secant lines to approximate it, starting from the given points' secant line.
- Author
- Samuel Pires
◆ TOLERANCE
for assert
for fabs for io operations
◆ func()
Continuous function for which we want to find the root.
- Parameters
-
- Returns
- The evaluation result of the function using the input value
22{
23 return x * x - 3.;
24}
◆ main()
Main function.
- Returns
- 0 on exit
77{
79 return 0;
80}
static void test()
Self-test implementations.
Definition secant_method.c:61
◆ secant_method()
double secant_method |
( |
double |
x0, |
|
|
double |
x1, |
|
|
double |
tolerance |
|
) |
| |
Root-finding method for a continuous function given two points.
- Parameters
-
x0 | One of the starting secant points |
x1 | One of the starting secant points |
tolerance | Determines how accurate the returned value is. The returned value will be within tolerance of the actual root |
- Returns
root of the function
if secant method succeed within the maximum number of iterations
-
-1
if secant method fails
37{
38 int n = 1;
39
40 while (n++ < NMAX)
41 {
42
43 double x2 = x1 -
func(x1) * (x1 - x0) / (
func(x1) -
func(x0));
44
45
46 x0 = x1;
47 x1 = x2;
48
49
50 if (fabs(x1 - x0) < tolerance)
51 return x2;
52 }
53
54 return -1;
55}
double func(double x)
Continuous function for which we want to find the root.
Definition secant_method.c:21
◆ test()
static void test |
( |
void |
| ) |
|
|
static |
Self-test implementations.
- Returns
- void
62{
63
68
69 printf("All tests have successfully passed!\n");
70}
double secant_method(double x0, double x1, double tolerance)
Root-finding method for a continuous function given two points.
Definition secant_method.c:36
#define TOLERANCE
for assert
Definition secant_method.c:13