-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewtonMethod.c
89 lines (66 loc) · 1.82 KB
/
NewtonMethod.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#define OUTPUT_FORMAT "%-8LG"
#define INPUT_FORMAT "%Lf"
#define TOL 1e-14L
/*
expect: f and fl as function with variable number of arguments. furthermore fl is mathematically the derivative of f
Compute the "root" of f using the Newton's method and return the "root"
*/
long double NewtonMethod( long double (*f)(int n, ...), long double (*df)(int n, ...), long double x0, long double tol, unsigned int *niter);
/* f(x) = x^5+x^4-3.3; root: 1.117329744559439*/
long double f(int n,...);
/* df(x) = 3*x^2 - 5 */
long double df(int n, ...);
int main(void)
{
long double x0;
long double x;
unsigned int niter = 0;
//x0 = 1.1173;
x0 = 0.5;
x = NewtonMethod(f, df, x0, TOL, &niter);
printf("%u iterations\n", niter);
printf("x = ");
printf(OUTPUT_FORMAT, x); printf("\n");
return 0;
}
long double NewtonMethod( long double (*f)(int n, ...), long double (*df)(int n, ...), long double x0, long double tol, unsigned int *niter)
{
long double k = 0.0;
unsigned int cont = 0;
while ( fabs( f(1, x0) ) > tol )
{
k = x0 - f(1, x0) / df(1, x0);
x0 = k;
cont++;
}
*niter = cont;
return x0;
}
/* 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;
}
/* df(x) = 5*x^4 + 4*x^3 */
long double df(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 = 5 * powl(x, 4.0) + 4 * powl(x, 3.0);
return value;
}