-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest1源.cpp
More file actions
46 lines (38 loc) · 1.41 KB
/
test1源.cpp
File metadata and controls
46 lines (38 loc) · 1.41 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
#include <iostream>
#include <vector>
// 定义原始函数
double f(double x) {
return 1 / (1 + x * x);
}
// 定义二次插值函数
double quadratic_interpolation(double x, double x0, double x1, double x2, double y0, double y1, double y2) {
return y0 * (x - x1) * (x - x2) / ((x0 - x1) * (x0 - x2)) + y1 * (x - x0) * (x - x2) / ((x1 - x0) * (x1 - x2)) + y2 * (x - x0) * (x - x1) / ((x2 - x0) * (x2 - x1));
}
int main() {
int n = 10; // 区间数
int N_values[] = { 10, 20 }; // 不同的N值
for (int k = 0; k < 2; k++) {
int N = N_values[k];
std::vector<double> x_values(N+1);
std::vector<double> interpolated_values(N+1);
for (int i = 0; i <= N; i++) {
x_values[i] = -5 + i * 10.0 / N;
}
for (int i = 0; i < N; i++) {
double x = x_values[i];
int j = i * n / N; // 确定所在区间
double x0 = -5 + j * 10.0 / n;
double x1 = -5 + (j + 1) * 10.0 / n;
double x2 = -5 + (j + 2) * 10.0 / n;
double y0 = f(x0);
double y1 = f(x1);
double y2 = f(x2);
interpolated_values[i] = quadratic_interpolation(x, x0, x1, x2, y0, y1, y2);
}
std::cout << "N=" << N << " 时的插值结果:" << std::endl;
for (int i = 0; i < N; i++) {
std::cout << "x = " << x_values[i] << ",此时值为 " << interpolated_values[i] << std::endl;
}
}
return 0;
}