求高手,用c++定义一个函数求 两个 二维数组 相对元素 的相对误差的最大值。

2024-11-23 01:37:59
推荐回答(1个)
回答(1):

#include
#include
#include

using namespace std;

double error_compare(double a, double b)
{
return fabs(a-b)/fabs(b);
}

double matrix_compare(double** a, double** b, unsigned int row, unsigned int col)
{
double max = 0.0;
double tmp = 0.0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
tmp = error_compare(a[i][j], b[i][j]);
if (max < tmp) {
max = tmp;
}
}
}
return max;
}

void test()
{
const unsigned int MAX_ROW = 100;
const unsigned int MAX_COL = 100;
double* test_a[MAX_ROW];
double* test_b[MAX_ROW];
srand((int)time(0));
double max = 0.0;
double tmp = 0.0;
for (int i = 0; i < MAX_ROW; ++i) {
test_a[i] = new double[MAX_COL];
test_b[i] = new double[MAX_COL];
for (int j = 0; j < MAX_COL; ++j) {
test_a[i][j] = rand();
test_b[i][j] = rand();
//cout< tmp = error_compare(test_a[i][j], test_b[i][j]);
if (max < tmp) {
max = tmp;
}
}
}
tmp = matrix_compare(test_a, test_b, MAX_ROW, MAX_COL);
if (tmp == max) {
cout< }
else {
cout<<"BUG! [max="< }
}
int main(int argc, char* argv[])
{
test();
return 0;
}