-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleLinearInterpolation.java
More file actions
79 lines (66 loc) · 2.9 KB
/
Copy pathSimpleLinearInterpolation.java
File metadata and controls
79 lines (66 loc) · 2.9 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
package heyingzhe;
public class SimpleLinearInterpolation {
// 计算欧氏距离
public static double euclideanDistance(double x1, double y1, double x2, double y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
// 线性插值,计算目标点 (x, y) 的值
public static double linearInterpolate(double x, double y, double x1, double y1, double z1,
double x2, double y2, double z2) {
// 计算权重
double d1 = euclideanDistance(x, y, x1, y1);
double d2 = euclideanDistance(x, y, x2, y2);
// 使用反距离加权法进行线性插值
return (z1 / d1 + z2 / d2) / (1 / d1 + 1 / d2);
}
// 对网格进行线性插值
public static double[][] linearInterpolationGrid(double[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
// 遍历网格,插值所有零值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 0.0) {
// 查找周围的四个已知点(上下左右)
if (i > 0 && i < rows - 1 && j > 0 && j < cols - 1) {
double f1 = grid[i-1][j]; // 左边
double f2 = grid[i+1][j]; // 右边
double f3 = grid[i][j-1]; // 上面
double f4 = grid[i][j+1]; // 下面
// 对于目标点 (i, j),计算线性插值
double z = linearInterpolate(i, j, i-1, j, f1, i+1, j, f2);
double z2 = linearInterpolate(i, j, i, j-1, f3, i, j+1, f4);
// 对这两个方向的插值结果进行平均(可以根据需求选择不同的合成方法)
grid[i][j] = (z + z2) / 2.0;
}
}
}
}
return grid;
}
// 打印二维数组
public static void printGrid(double[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.printf("%.2f ", grid[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
// 示例数据
double[][] grid = new double[10][10]; // 创建一个10x10的网格
// 给部分网格赋值降雨量数据
grid[2][2] = 5.0;
grid[5][5] = 10.0;
grid[7][8] = 3.0;
// 打印原始网格
System.out.println("原始网格:");
printGrid(grid);
// 进行线性插值
double[][] interpolatedGrid = linearInterpolationGrid(grid);
// 输出插值后的网格
System.out.println("\n插值后的网格:");
printGrid(interpolatedGrid);
}
}