-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHan_Question1.cpp
More file actions
89 lines (67 loc) · 2.59 KB
/
Copy pathHan_Question1.cpp
File metadata and controls
89 lines (67 loc) · 2.59 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
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
// defining a function for f(x), the roots of which we have to find
double f(double x)
{
return sin(x*x);
}
// defining a structure of the type "output" which will store one integer (number of iterations) and one double (location of the root)
struct output
{
int n;
double c;
string s;
};
// function for performing the bisection method given the interval and tolerance
output bisection_method(double a, double b, double e) // a and b define the interval, and e is the tolerance value
// it returns a value of the type 'output' which we defined earlier
{
output bisection_output;
if (f(a)*f(b) < 0){ // if the product is negative, it means that the root lies between a and b (because f(a) and f(b) have opposite signs)
//output bisection_output;
bisection_output.n = 0; // to store number of iterations
while ((b-a) >= e) {
bisection_output.n++;
bisection_output.c = (a+b)/2; // midpoint of the interval
if (f(bisection_output.c) == 0) // if the root lies at the midpoint c, then print it
cout << "The root of f(x) is " << bisection_output.c << endl;
else // we consider the intervals to the left and right of the midpoint and evaluate the same condition as before
if (f(bisection_output.c)*f(a) < 0)
b = bisection_output.c;
else
a = bisection_output.c;
}
return bisection_output;
}
else{
bisection_output.s = "NOT FOUND";
}
}
int main()
{
string ans; // string to store user's answer to the question in line 77
do {
cout << "Enter the value of the lower bound a: " << endl;
double a;
cin >> a;
cout << "Enter the value of the upper bound b: " << endl;
double b;
cin >> b;
cout << "Enter the tolerance value e: " << endl;
double e;
cin >> e;
if (bisection_method(a, b, e).s== "NOT FOUND"){
cout << "Root not found" << endl;
}
else{
cout << "Root: " << bisection_method(a, b, e).c << endl;
cout << "Number of iterations N = " << bisection_method(a, b, e).n << endl;
}
cout << "Do you want to do another calculation? (yes/no) " << endl;
cin >> ans;
}
while (ans == "yes"); //the use of the do while loop means that the program runs once, and then asks the user if they want to repeat it
return 0;
}