本文介绍了matlab和c ++中的精度差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对用C ++和Matlab编写的算法进行等价测试。
该算法在时间上包含某种循环,运行次数超过1000次。它具有算术运算和一些数学函数。

I am trying to make equivalence tests on an algorithm written in C++ and in Matlab.The algorithm contains some kind of a loop in time and runs more than 1000 times. It has arithmetic operations and some math functions.

我手动为两个平台提供初始输入(如a = 1.767,b = 6.65,...)我检查那些输入的十六进制表示,它们是相同的。所以输入没有问题。并通过16个十进制数字的文本文件获得c ++的输出到matlab。 (我使用setprecision(32)语句)

I feed the initial inputs to both platforms by hand (like a=1.767, b=6.65, ...) and when i check the hexadecimal representations of those inputs they are the same. So no problem for inputs. And get the outputs of c++ to matlab by a text file with 16 decimal digits. (i use "setprecision(32)" statement)

但是这里的问题;虽然在两个代码的第614步后,所有的结果是完全一样的,在615的步骤我得到一个差异大约2.xxx..xxe-19?在这一步之后,错误变得越来越大,在运行结束时它大约是5.xx..xxe-14。

But here comes the problem; although after the 614'th step of both code, all the results are exactly the same, on the step of 615 I get a difference about 2.xxx..xxe-19? And after this step the error becomes larger and larger, and at the end of the runs it is about 5.xx..xxe-14.

0x3ff1 3e42 a211 6cca- - > [C ++函数] ---> 0x3ff4 7619 7005 5a42

0x3ff1 3e42 a211 6cca--->[C++ function]--->0x3ff4 7619 7005 5a42

0x3ff1 3e42 a211 6cca ---> [MATLAB函数] ---> ans

0x3ff1 3e42 a211 6cca--->[MATLAB function]--->ans

ans - 0x3ff4 7619 7005 5a42

ans - 0x3ff4 7619 7005 5a42

= 2.xxx..xxe-19

= 2.xxx..xxe-19

我搜索了如何matlab行为的数字,并发现真正有趣的东西,如反规范尾数。虽然realmin是关于e-308,通过反正规化尾数matlab有关于e-324的最小实数。另外,matlab比c更多的数字pi或exp(1)。

I searched how matlab behaves the numbers and found really interesting things like "denormalized mantissa". While realmin is about e-308, by denormalizing the mantissa matlab has the smallest real number about e-324. Further matlab holds many more digits for "pi" or "exp(1)" than that of c++.

另一方面,matlab帮助说,无论什么格式显示器,matlab在内部使用双精度。

On the other hand, matlab help says that whatever the format it displays, matlab uses the double precision internally.

所以,我真的很感激,如果有人解释这些差异的确切原因是什么?我们如何对matlab和c ++进行等价测试?

So,I'd really appreciate if someone explains what the exact reason is for these differences? How can we make equivalence tests on matlab and c++?

推荐答案

A 容忍超越函数(cos,sin,exp等)的最后一位的错误。所以你不能指望MATLAB和C之间完全相同的结果(甚至不同的C代码编译在不同的编译器)。

A similar discussion occurred before, the conclusion was that IEEE 754 tolerates error in the last bit for transcendental functions (cos, sin, exp, etc..). So you can't expect exactly same results between MATLAB and C (not even same C code compiled in different compilers).

这篇关于matlab和c ++中的精度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:58