-3

I recently discovered, quite harshly, that Matlab's dlmread and dlmwrite don't store numerical values at double accuracy. It effects my code, and I need to store big arrays with more precision.

A (not) working example :

pi1 = pi;
dlmwrite('pi',pi1);
pi2 = dlmread('pi');
pi1-pi2

ans =

-7.3464e-06

While I'd expect machine-error answer, of 10^-14 accuracy.

I'd much rather keep using a simple function as dlmwrite, but I will consider other solutions.

Thanks

Amir Sagiv
  • 376
  • 5
  • 23
  • 2
    RTFM: [The default precision is 5 significant digits and it supports C-style format strings](http://www.mathworks.com/help/matlab/ref/dlmwrite.html#input_argument_namevalue_precision). As an alternative, `dlmwrite` is a wrapper for the lower-level [`fwrite`](http://www.mathworks.com/help/matlab/ref/fwrite.html) function. – sco1 Jan 02 '16 at 14:07

1 Answers1

3

You can get more precise results by using the precision property of the function. Check this example:

format long
S = pi * rand

S =

   2.869454879612631

dlmwrite('test1.txt',S,'precision','%10.3f');
dlmwrite('test2.txt',S,'precision','%10.5f');
dlmwrite('test3.txt',S,'precision','%10.9f');
dlmwrite('test3.txt',S,'precision','%2.14f');

The result is as follows:

  • test1.txt with 3 decimals 2.869

  • test2.txt with 5 decimals 2.86945

  • test3.txt with 9 decimals 2.869454880

  • test4.txt with 14 decimals 2.86945487961263

NKN
  • 6,482
  • 6
  • 36
  • 55