why is there significant double precision difference between Matlab and Mathematica?

我与影子孤独终老i 提交于 2019-12-11 00:07:30

问题


I created a random double precision value in Matlab by

x = rand(1,1);

then display all possible digits of x by

vpa(x,100)

and obtain:

0.2238119394911369 7971853298440692014992237091064453125

I save x to a .mat file, and import it into Mathematica, and then convert it:

y = N[FromDigits[RealDigits[x]],100]

and obtain:

0.2238119394911369 0000

Then go back to Matlab and use (copy and paste all the Mathematica digits to Matlab):

 vpa(0.22381193949113690000,100)

and obtain:

0.22381193949113689 64518061375201796181499958038330078125

Why there is significant difference between the same double precision variable?

How to bridge the gap when exchanging data between Mathematica and Matlab?


回答1:


You can fix this problem by using ReadList instead of Import. I have added some demo steps below to explore displayed rounding and equality. Note the final test d == e? is False in Mathematica 7 but True in Mathematica 9, (with all the expected digits). So it looks like some precision has been added to Import by version 9. The demo uses a demo file.

Contents of demo.dat:

0.22381193949113697971853298440692014992237091064453125
"0.22381193949113697971853298440692014992237091064453125"

Exploring:-

a = Import["demo.dat"]
b = ReadList["demo.dat"]
a[[1, 1]] == a[[2, 1]]
b[[1]] == b[[2]]
a[[1, 1]] == b[[1]]
a[[1, 1]] == ToExpression@b[[2]]
b[[1]] // FullForm
c = First@StringSplit[ToString@FullForm@b[[1]], "`"]
b[[2]]
ToExpression /@ {c, b[[2]]}
d = N[FromDigits[RealDigits[a[[1, 1]]]], 100]
e = N[FromDigits[RealDigits[b[[1]]]], 100]
d == e



回答2:


The precision is as expected for double values. A double has a 53 bit fraction, thus the precision is about 53*log(10)/log(2)=16 significant digits. You have 16 significant digits, it works as expected.



来源:https://stackoverflow.com/questions/19808261/why-is-there-significant-double-precision-difference-between-matlab-and-mathemat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!