-
Notifications
You must be signed in to change notification settings - Fork 0
/
SecantMethod.c
71 lines (51 loc) · 1.37 KB
/
SecantMethod.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#define OUTPUT_FORMAT "%-8LF"
#define INPUT_FORMAT "%Lf"
#define TOL 1e-6L
/*
Compute the "root" of f using the Secant method and return the "root"
*/
long double SecantMethod( long double (*f)(int n, ...), long double x0, long double x1, long double tol, unsigned int *niter);
/* f(x) = x^5+x^4-3.3; root: 1.117329744559439*/
long double f(int n,...);
int main(void)
{
long double x0, x1, x;
unsigned int niter = 0;
x0 = 2;
x1 = 3;
x = SecantMethod(f, x0, x1, TOL, &niter);
printf("%u iterations\n", niter);
printf("x = ");
printf(OUTPUT_FORMAT, x ); printf("\n");
return 0;
}
long double SecantMethod( long double (*f)(int n, ...), long double x0, long double x1, long double tol, unsigned int *niter)
{
long double k = 0.0;
unsigned int cont = 0;
while( fabs( f(1, x1) ) > tol )
{
k = x1 - f(1, x1) * (x0 - x1) / ( f(1, x0) - f(1, x1) );
x0 = x1;
x1 = k;
cont++;
}
*niter = cont;
return x1;
}
/* f(x) = x^5 + x^4 - 3.3 */
long double f(int n,...)
{
va_list arg_list;
long double value = 0.0;
long double x;
va_start(arg_list, n);
x = va_arg(arg_list, long double);
value = powl(x, 5.0) + powl(x, 4.0) - 3.3;
return value;
}