【C++学习】数据读入-格式2(多列)
【C++学习】数据读入-格式3(二维表)
上述方法可将文本文件中数据存储为指针数组。
1. 功能概述
1.1 功能效果
实现对指针数组进行插值运算,包括一维和二维线性插值。
1.2 使用方法
- 输入要求:输入插值自变量、应变量、数据个数和插值点;
- 输出结果:
2. 注意事项
- 使用指针数组时需要特别注意数据个数,注意本例的使用;
- 通过类枚举intMethod选择不同的插值方式,inner为内插值,extra为外插值。
3. 详细代码
Interp.h
/*
* Auther: sanfan66
*
* Date | Change
*--------------------------------------------
* 231017 | <record>: None→Version 0.0a,Original finished
* | (describe): One/two-dimensional interpolation
* | !warning!: Independent variables need an array of pointers
*/
#pragma once
enum class intMethod {
inner,
extra
};
class Interp {
public:
double Dim1(const double *X, const double *Y, const int n, const double x, const intMethod method);
double Dim2(const double *X, const double *Y, const double *const*Z, const int row, const int col, const double x, const double y, const intMethod method);
private:
int findIndex(const double *X, const int n, double *x, const intMethod method);
};
Interp.cpp
#include "Interp.h"
#include <iostream>//cout
using namespace std;//cout
constexpr double EPS = 1e-7;
int Interp::findIndex(const double *X, const int n, double *x, intMethod method) {
/* 判断插值自变量是否递增,并且找到插值位置 */
int index = 0;
for (int i = 0; i < n - 1; i++) {
if (X[i + 1] - X[i] < -EPS) {
cout << "第" << i + 2 << "个数不递增" << endl;
system("Pause");
exit(0);
}
if (X[i] <= *x && *x <= X[i + 1]) {
index = i;
break;
}
else if (*x < X[0]) {
index = 0;
switch (method) {
case intMethod::inner:
*x = X[0];
break;
case intMethod::extra:
break;
default:
cout << "Interp::Dim1选择intMethod::inner(内插值)或intMethod::extra(外插值)" << endl;
system("Pause");
exit(0);
break;
}
break;
}
else if (*x > X[n - 1]) {
index = n - 2;
switch (method) {
case intMethod::inner:
*x = X[n - 1];
break;
case intMethod::extra:
break;
default:
cout << "Interp::Dim1选择intMethod::inner(内插值)或intMethod::extra(外插值)" << endl;
system("Pause");
exit(0);
break;
}
break;
}
}
return index;
}
double Interp::Dim1(const double *X, const double *Y, const int n, const double x, const intMethod method) {
/* 一维插值 */
double intX = x;
int index = findIndex(X, n, &intX, method);
return Y[index] + (Y[index + 1] - Y[index]) / (X[index + 1] - X[index])*(intX - X[index]);
}
double Interp::Dim2(const double *X, const double *Y, const double *const*Z, const int row, const int col, const double x, const double y, const intMethod method) {
/* 二维插值 */
double intX = x;
int indexRow = findIndex(X, row, &intX, method);
double intY = y;
int indexCol = findIndex(Y, col, &intY, method);
double z1 = Z[indexRow][indexCol] + (Z[indexRow][indexCol + 1] - Z[indexRow][indexCol]) / (Y[indexCol + 1] - Y[indexCol])*(intY - Y[indexCol]);
double z2 = Z[indexRow + 1][indexCol] + (Z[indexRow + 1][indexCol + 1] - Z[indexRow + 1][indexCol]) / (Y[indexCol + 1] - Y[indexCol])*(intY - Y[indexCol]);
return z1 + (z2 - z1) / (X[indexRow + 1] - X[indexRow])*(intX - X[indexRow]);
}