dlmread adds low precision digits

조회 수: 11 (최근 30일)
Arnaud WILHELM
Arnaud WILHELM 2019년 8월 27일
댓글: Arnaud WILHELM 2019년 8월 28일
Hello all,
I'm using dlmread to import datas and when the datas contains integers and float numbers, dlmread sometimes makes an error on the last digit of the output precision.
I'm not sure I am clear, so here is an example :
If my text file ('test.rpt') contains only the row :
1 10.8000 31. 10.5001
the command
A = dlmread('test.rpt')
gives back :
A =
1.000000000000000 10.800000000000001 31.000000000000000 10.500100000000000
I don't understand why this 10e-15 is added on the second number. Ok, it's not a big error, but it prevent me from easly comparing two values...
Does anyone know how to prevent this behaviour ?
  댓글 수: 6
dpb
dpb 2019년 8월 27일
> x=10.8
x =
10.8000
>> fprintf('%.15f\n',x)
10.800000000000001
>>
so it doesn't matter how you enter it, 10.8 is not exactly representable.
"I don't remember seeing this when using fscanf and specifing a number format."
Probably because you just didn't notice until you did try to do an exact comparison on floating point values.
>> fprintf('%.15f\n',round(x,1))
10.800000000000001
>>
It's doing the best it can within the constraints of IEEE floating point representation.
Adam Danz
Adam Danz 2019년 8월 27일
편집: Adam Danz 2019년 8월 27일
Ah, ok then. Thanks dpb & James Tursa .

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2019년 8월 27일
편집: James Tursa 2019년 8월 27일
Any function (dlmread, fscanf, etc) in any language (MATLAB, C, etc.) reading text numbers into floating point will have this issue. You may not have noticed it before, but it has always been there. With some exceptions (integers, etc), in general you simply can't represent many decimal numbers exactly in IEEE binary floating point format. For your numbers, here are the exact conversions:
>> sprintf('%.50f',1)
ans =
'1.00000000000000000000000000000000000000000000000000'
>> sprintf('%.50f',10.8)
ans =
'10.80000000000000071054273576010018587112426757812500'
>> sprintf('%.50f',31)
ans =
'31.00000000000000000000000000000000000000000000000000'
>> sprintf('%.50f',10.5001)
ans =
'10.50009999999999976694198267068713903427124023437500'
Integers (that are not too big) it does fine with, but your other decimal numbers cannot be represented internally exactly. Read the links that dpb has provided.
  댓글 수: 1
Arnaud WILHELM
Arnaud WILHELM 2019년 8월 28일
All right, I understand now.
Thanks everyone for these anwsers !

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by