トレースには次の性質がある。
\begin{align}
tr (A+B) = tr A + tr B
\end{align}
今回はこれをC++で計算する。
実行結果
1,2,3,
4,5,6,
7,8,9,
10,11,12,
13,14,15,
16,17,18,
tr A+ tr B->57
tr (A + B)->57
確かに一致している。
ソースコード。
#include <iostream>
void show(double*, int, int);
double Fnorm(double*, int, int);
double trace(double*, int, int);
double* add(double*, double*, int, int);
int main() {
int m = 3, n = 3;
double sum = 0;
double* x;
double* y;
x = new double[m * n];
y = new double[m * n];
for (int i = 0; i < m * n; i++) {
x[i] = i + 1;
}
for (int i = 0; i < m * n; i++) {
y[i] = i + 10;
}
show(x, n, m);
std::cout << std::endl;
show(y, n, m);
std::cout << std::endl;
std::cout << "tr A+ tr B->" << trace(x, n, m) + trace(y, n, m) << std::endl;
std::cout << "tr (A + B)->" << trace(add(x, y, m, n), n, m);
}
double Fnorm(double* x, int n, int m) {
double norm = 0;
for (int i = 0; i < n * m; i++) {
norm += std::pow(x[i], 2);
//std::cout << norm << std::endl;
}
std::cout << std::endl;
return std::sqrt(norm);
}
void show(double* x, int n, int m) {
int count = 0;
for (int i = 0; i < m * n; i++) {
count += 1;
std::cout << x[i] << ",";
if (count == m) {
std::cout << std::endl;
count = 0;
}
}
}
double trace(double* x, int n, int m) {
int sum = 0, pos = 0;
if (m != n) {
std::cout << "error" << std::endl;
return 0;
}
else {
for (int i = 0; i < m * n; i++) {
if (pos == i) {
sum += x[i];
pos += n + 1;
}
}
}
return sum;
}
double* add(double* A, double* B, int n, int m) {
int sum = 0, pos = 0;
double* x;
x = new double[m * n];
for (int i = 0; i < m * n; i++) {
x[i] = A[i] + B[i];
}
return x;
}
コメント