-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbisection.c
More file actions
executable file
·94 lines (84 loc) · 1.8 KB
/
bisection.c
File metadata and controls
executable file
·94 lines (84 loc) · 1.8 KB
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
92
93
94
/**
* Author: Katie Gerot
* Date: 09/20/2019
* Class: CSCE 440
*
* Program computing the Bisection Method with the following equations:
* (a) 3x^3 - 2x^2 + 5x - 2e^x + 1
* (b) x^4 + 3x^2 - 2
* (c) 3x - x^2 - e^x - 2
* (d) x - cos(x)
**/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
double f(double x, char e);
int main(int argc, char **argv) {
const double TOL = 0.0001; //tolerance
const int MAX_I = 50; //maximum iterations
char eq = argv[1][0]; //equation, either a, b, c, or d
double a, b, fa, fp, p; // endpoints
switch(eq) { //sets correct interval
case 'a':
a = -1;
b = 1;
break;
case 'b':
a = 0;
b = 2;
break;
case 'c':
a = -2;
b = 2;
break;
case 'd':
a = -2;
b = 2;
break;
default: exit(1);
}
printf("i\tp\n"); //headers for output table
int i = 0;
fa = f(a, eq); //f(a)
//BISECTION METHOD
while(i <= MAX_I) {
i++;
printf("%2d", i);
p = a + (b - a)/2;
fp = f(p, eq); //f(p)
if(fp == 0 || (b - a)/2 < TOL) { // if a root is found or the midpoint is
// within a certain tolerance
printf("%14.6lf\n", p);
break;
}
if(fa * fp > 0) { // if the product is positive or not zero
a = p;
fa = fp;
} else { // if the product is negative or zero
b = p;
}
printf("%14.6lf\n", p);
}
return 0;
}
/**
* Given x, this function will compute the equation designated by char e
**/
double f(double x, char e) {
switch(e) {
case 'a':
return (3 * pow(x, 3)) -
(2 * pow(x, 2)) +
(5 * x) - (2 * pow(M_E, x)) + 1;
case 'b':
return pow(x, 4) +
(3 * pow(x, 2)) - 2;
case 'c':
return (3 * x) -
pow(x, 2) +
pow(M_E, x) - 2;
case 'd':
return x- cos(x);
default: exit(1);
}
}