Search code examples
matlabwolfram-mathematicadigitsdouble-precision

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


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?


Solution

  • 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