Why does MATLAB returns a different value when we use a function?

Why do I get different ans values?
>> number = single(0.01);
>> floor( log10( abs( number ) ) )
ans =
-2
>> func( number )
ans =
-3
The func is described below.
function B = func( A )
B = floor( log10( abs( A ) ) );
end
MATLAB should return -2 and does it on command window. But -3 is returned when we use function.
>> num2str( double(0.01), 17 )
ans =
0.01
>> num2str( single(0.01), 8 )
ans =
0.0099999998
Why does MATLAB correct it only by command window?

답변 (1개)

Roger Stafford
Roger Stafford 2016년 4월 25일

0 개 추천

As you may be aware, in neither double precision nor single precision floating point format numbers such as you are using here, can the number .01 be exactly represented, since your computer uses binary numbers, not decimal numbers. However, double precision can come very much closer to it than single precision, and that accounts for the difference in results. It has nothing to do with whether a command window is used or a function performs the computation. It depends entirely on those numbers' formats.

댓글 수: 1

Thank you for your answer.
> It depends entirely on those numbers' formats.
I think so, too. But, it returns -2.

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2016년 4월 25일

댓글:

2016년 4월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by