Matlab和C ++双精度 [英] Matlab vs C++ Double Precision

查看:651
本文介绍了Matlab和C ++双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些代码从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的 格式长 只打印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:

  • 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 ++双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆