提问人:skm 提问时间:10/6/2023 最后编辑:skm 更新时间:10/6/2023 访问量:77
Python 和 C++ 中矩阵乘法中的不同浮点精度
Different floating point precision in Matrix multiplication in Python and C++
问:
我正在尝试做一件非常简单的事情
- 取一个正方形的二维数组
- 接受它的转置
- 将数组与其转置相乘
我正在尝试在 C++ 和 Python 中执行上述步骤,如以下程序所示:
C++程序:
#include <iostream>
#include <iomanip> // For setw
int main() {
float R[16] = {
0.5, 0.63245553, -0.5, 0.31622777,
0.5, 0.31622777, 0.5, -0.63245553,
0.5, -0.31622777, 0.5, 0.63245553,
0.5, -0.63245553, -0.5, -0.31622777
};
const int nRows = 4;
const int nCols = 4;
float result[nRows][nRows] = { 0 };
// Perform matrix multiplication
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nRows; j++) {
for (int k = 0; k < nCols; k++) {
result[i][j] += R[i * nCols + k] * R[j * nCols + k];
}
}
}
// Print the result with left-aligned columns and a padding of 15 characters
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nRows; j++) {
std::cout << std::left << std::setw(15) << result[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
Python程序:
import numpy as np
R = np.array([
0.5, 0.63245553, -0.5, 0.31622777,
0.5, 0.31622777, 0.5, -0.63245553,
0.5, -0.31622777, 0.5, 0.63245553,
0.5, -0.63245553, -0.5, -0.31622777
]).reshape(4, 4)
result = np.dot(R, R.T)
# Print the result
print(result)
问题:从上面的程序中可以看出,我使用的是完全相同的输入数组/矩阵。但是乘法子结果的精度是完全不同的。
除对角线外,大多数值都大相径庭,精度差异巨大。如何在两种语言中获得相同的精度?为什么某些元素的标志甚至被翻转了?
C++ 结果:
1 -1.49012e-08 0 -7.45058e-09
-1.49012e-08 1 0 0
0 0 1 -1.49012e-08
-7.45058e-09 0 -1.49012e-08 1
Python 结果:
[[1.00000000e+00 2.77555756e-17 0.00000000e+00 5.32461714e-11]
[2.77555756e-17 1.00000000e+00 5.32461852e-11 0.00000000e+00]
[0.00000000e+00 5.32461852e-11 1.00000000e+00 2.77555756e-17]
[5.32461714e-11 0.00000000e+00 2.77555756e-17 1.00000000e+00]]
答: 暂无答案
评论