-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtvi.c
59 lines (52 loc) · 1.35 KB
/
tvi.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
//ponteiro pra função pointer to function
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
float func(int x)
{
float ans = pow(x,3) + 4*x-2- exp(pow(x,2)-x);
return ans; //retorna f(x)
}
//@param f calls func
//@param a,b used in the intermediate value theorem as extremes
float tvi(float (*f)(int), int a, int b)
{
int MAX_N = 1486618625;
float TOL = 0.000000058;
int t1 = (*f)(a);
int t2 = (*f)(b);
float mid = (a+b)/2;
int N = 0;
while(N<MAX_N)
{
if (mid = 0 || (b-a)/2 < TOL)
{
if(mid == 0)printf("mid = 0\n");
if((b-a)/2 < TOL)printf("TOL\n");
printf("ENCONTREI!");
printf("%.2f\n",mid);
return mid;
}
if ((*f)(a)>0 && (*f)(b)>0 ||(*f)(a)<0 && (*f)(b)<0) //cria novo intervalo
{
a = mid;
}
b=mid;
N++;
}
}
int main()
{
tvi(func,0.555, 5);
}
// N ← 1
// while N ≤ NMAX do // limit iterations to prevent infinite loop
// c ← (a + b)/2 // new midpoint
// if f(c) = 0 or (b – a)/2 < TOL then // solution found
// Output(c)
// Stop
// end if
// N ← N + 1 // increment step counter
// if sign(f(c)) = sign(f(a)) then a ← c else b ← c // new interval
// end while
// Output("Method failed.") // max number of steps exceeded