4

How to avoid the rounding error, when exporting data like this:

ra = Range[0.004, 0.074, 0.0005];
Export["range.txt", ra]

The result is this: enter image description here

Kay
  • 1,035
  • 7
  • 19
  • Why? When you read this data with another program that uses floating point, the error will grow back anyway. – John Doty Jun 28 '18 at 11:24
  • This is just an example, but it inflates the size of my files unnecessarily. As I am handling a huge amount of data I have to figure out some efficiency. – Kay Jun 28 '18 at 11:56
  • Try something like ToString@NumberForm[#, {10, 4}] & /@ ra before exporting. Does that help? – halirutan Jun 28 '18 at 12:02
  • 1
    Alternatively to @halirutan's suggestion, you can use Export["range.txt", NumberForm[ra, {10, 4}], "List"] – Lukas Lang Jun 28 '18 at 12:39
  • Also, this question is strongly related – Lukas Lang Jun 28 '18 at 12:40
  • 1
    but it inflates the size of my files unnecessarily If size is an issue why are you not writing binary files ? Not only will that ensmallen your files, it will circumvent the problem which prompted your question, and make reading/writing faster. Win win win. – High Performance Mark Jun 29 '18 at 05:57

1 Answers1

5

You may use SetPrecision on your list, ra.

ExportString[SetPrecision[ra, 6], "Table"]
0.004
0.0045
0.005
0.0055
0.006
0.0065
0.007
0.0075
0.008
0.0085
0.009
0.0095
0.01
0.0105
...

Hope this helps.

Edmund
  • 42,267
  • 3
  • 51
  • 143