问题描述
我正在将一些代码从 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++ 双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!