-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApproximation_Functions.cpp
More file actions
73 lines (61 loc) · 1.64 KB
/
Approximation_Functions.cpp
File metadata and controls
73 lines (61 loc) · 1.64 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
#include <iostream>
#include <string>
#include <cmath>
#include <stdexcept>
using namespace std;
// 定義された関数 f(x)
double my_function(double x) {
if (1 - x < -1.0 ||
1 - x > 1.0 ||
2 * x - x * x < 0)
{
// 定義域外
return NAN;
}
return M_PI - 3.0 * asin(1 - x) + (6.0 - 6.0 * x) * sqrt(2 * x - x * x);
}
double root(float a, float b, int n) {
if (isnan(my_function(a)) ||
isnan(my_function(b)))
{
cout << "Error: 関数が定義域外です。" << endl;
return NAN;
}
if (my_function(a) * my_function(b) > 0) {
cout << "Error: 区間内に解がありません。" << endl;
return NAN;
}
float left = a;
float right = b;
for (int i = 0; i < n; i++) {
float mid = (left + right) / 2.0;
if (isnan(my_function(mid))) {
cout << "Error: 計算途中に定義域外です。" << endl;
return NAN;
}
if (my_function(mid) == 0) {
return mid;
}
if (my_function(mid) < 0) {
left = mid;
} else {
right = mid;
}
}
return (left + right) / 2.0;
}
int main() {
int n;
float a, b;
cout << "関数の解を求めたい区間 [a, b] を入力して下さい: ";
cin >> a >> b;
cout << "近似の回数もしくは精度 (ループ数) を入力して下さい: ";
cin >> n;
double approx = root(a, b, n);
if (isnan(approx)) {
cout << "解を求めるに失敗しました。" << endl;
} else {
cout << "近似解: " << approx << endl;
}
return 0;
}