問題描述
我正在將一些代碼從 Matlab 移植到 C++.
I am porting some code from Matlab to C++.
在 Matlab 中
format long
D = 0.689655172413793 (this is 1.0 / 1.45)
E = 2600 / D
// I get E = 3.770000000000e+03
在 C++ 中
double D = 0.68965517241379315; //(this is 1.0 / 1.45)
double E = 2600 / D;
//I get E = 3769.9999999999995
這對我來說是個問題,因為在兩種情況下我都必須四舍五入到 0(Matlab 的修復),在第一種情況下(Matlab)變成 3770,而在第二種情況下(C++)變成 3769.
It is a problem for me because in both cases I have to do rounding down to 0 (Matlab's fix), and in the first case (Matlab) is becomes 3770, whereas in the second case (C++) it becomes 3769.
我意識到這是因為 C++ 案例中另外兩個最低有效數字15".鑒于 Matlab 似乎只能以雙精度存儲多達 15 個有效數字的精度(如上所示 - 0.689655172413793),我如何有效地告訴 C++ 忽略后面的15"?
I realise that it is because of the two additional least significant digits "15" in the C++ case. Given that Matlab seems to only store up to 15 significant digits of precision in double precision (as shown above - 0.689655172413793), how can I effectively tell C++ to ignore the "15" at the back?
所有計算均以雙精度完成.
All calculations are done in double precision.
推薦答案
您對 C++ 和 MATLAB 打印雙精度值的不同方式感到困惑.MATLAB 的 format long
只打印15 有效數字,而 C++ 打印 17 有效數字.在內部兩者使用相同的數字:IEEE 754 64 位浮點數.為了在 MATLAB 中重現 C++ 行為,我定義了一個 匿名函數 disp17
打印 17 位有效數字的數字:
You got confused by the different ways C++ and MATLAB are printing double values. MATLAB's format long
only prints 15 significant digits while C++ prints 17 significant digits. Internally both use the same numbers: IEEE 754 64 bit floating point numbers. To reproduce the C++-behaviour in MATLAB, I defined a anonymous function disp17
which prints numbers with 17 significant digits:
>> disp17=@(x)(disp(num2str(x,17)))
disp17 =
@(x)(disp(num2str(x,17)))
>> 1.0 / 1.45
ans =
0.689655172413793
>> disp17(1.0 / 1.45)
0.68965517241379315
您在 MATLAB 和 C++ 中看到的結果是相同的,它們只是打印不同數量的數字.如果你現在繼續使用相同的常量在兩種編程語言中,你會得到相同的結果.
You see the result in MATLAB and C++ is the same, they just print a different number of digits. If you now continue in both programming languages with the same constant, you get the same result.
>> D = 0.68965517241379315 %17 digits, enough to represent a double.
D =
0.689655172413793
>> ans = 2600 / D %Result looks wrong
ans =
3.770000000000000e+03
>> disp17(2600 / D) %But displaying 17 digits it is the same.
3769.9999999999995
打印 17 或 15 位數字的背景:
The background for printing 17 or 15 digits:
- Adouble 需要在不丟失精度的情況下存儲 17 個有效數字,這是 C 打印的內容.
- 對于最多 15 位數字,任何數字都可以從字符串轉換為雙精度字符串并返回原始數字,這正是 MATLAB 所做的.
- A double requires 17 significant digits to be stored without precision loss, which is what C prints.
- For up to 15 digits any number can be converted from string to double to string and results back in the original number, which is what MATLAB does.
這篇關于Matlab 與 C++ 雙精度的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!