-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBisection.c
91 lines (65 loc) · 1.7 KB
/
Bisection.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
90
91
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#define TOL 1e-6L
#define OUTPUT_FORMAT "%-8LG"
#define INPUT_FORMAT "%Lf"
/*
expect: f as function with variable number of arguments.
compute the simple Bisection method.
*/
long double bissec( long double(f)(int, ...), long double a, long double b, long double tol, unsigned int *niter);
long double myfunction1(int, ...);
long double myfunction2(int, ...);
int main(void)
{
long double a, b, x;
unsigned int niter = 0;
a = -4;
b = 4;
x = bissec(myfunction2, a, b, TOL, &niter);
printf("%u iterations\n", niter);
printf("x = %LG\n", x);
return 0;
}
/* f(x) = x^5 + x^4 - 3.3*/
long double myfunction1(int n, ...)
{
long double value = 0.0;
va_list arg_list;
va_start(arg_list, n);
long double x = va_arg(arg_list, long double);
value = powl(x,5.0) + powl(x, 4.0) - 3.3;
return value;
}
/* f(x) = (x−2)^2 * (x+1) * (x+5)*/
long double myfunction2(int n, ...)
{
long double value = 0.0;
va_list arg_list;
va_start(arg_list, n);
long double x = va_arg(arg_list, long double);
value = powl(x-2, 2.0) * (x + 1) * ( x + 5);
va_end(arg_list);
return value;
}
long double bissec( long double(f)(int, ...), long double a, long double b, long double tol, unsigned int *niter)
{
long double error = LONG_MAX;
long double c = 0.0;
unsigned int cont = 0;
while( error > tol)
{
c = (a+b)/2;
if( f(1, a)*f(1,c) < 0 )
b = c;
else if( f(1, b)*f(1, c) < 0)
a = c;
error = fabs(f(1, c));
cont++;
}
*niter = cont;
return c;
}