floating-point arithmetic

5 ビュー (過去 30 日間)
Javad Farzi
Javad Farzi 2022 年 11 月 8 日
コメント済み: Walter Roberson 2022 年 11 月 15 日
It is obvious that
|0.1234-0.123| = 0.0004
however, the following Matlab result is a little bit different!
>> 0.1234-0.123
ans =
3.999999999999976e-04
I think this happens because the IEEE754 conversion of 0.1234 and 0.123 have infinite digits.
Does anyone have more explanation?

回答 (2 件)

Star Strider
Star Strider 2022 年 11 月 8 日
編集済み: Star Strider 2022 年 11 月 12 日
I think this happens because the IEEE754 conversion of 0.1234 and 0.123 have infinite digits.’
Correct.
Does anyone have more explanation?
I doubt it. Your explanation about covers it. (The relevant MATLAB documentation is in Floating-Point Numbers.)
.
EDIT — (12 Nov 2022 at 11:44)
In double precision we can trust on about 15 decimal digits.In double precision we can trust on about 15 decimal digits.
See the eps function for details —
format long
FPP = eps
FPP =
2.220446049250313e-16
FPP = 1/eps
FPP =
4.503599627370496e+15
FPPlog2 = log2(eps)
FPPlog2 =
-52
FPPlog2 = log2(1/eps)
FPPlog2 =
52
.

James Tursa
James Tursa 2022 年 11 月 8 日
編集済み: James Tursa 2022 年 11 月 8 日
"... the IEEE754 conversion of 0.1234 and 0.123 have infinite digits ..."
Not sure what you mean by this statement. Neither of these numbers can be represented exactly in IEEE double precision floating point which of course uses a finite number of binary bits. Maybe you mean an exact conversion of these specific decimal numbers to binary would require an infinite number of binary bits?
The exact binary-to-decimal conversions of the numbers that are stored (the closest representable values to the decimal numbers above) are:
fprintf('%.56f',0.1234)
0.12339999999999999580335696691690827719867229461669921875
fprintf('%.52f',0.123)
0.1229999999999999982236431605997495353221893310546875
fprintf('%.56f',0.1234 - 0.123)
0.00039999999999999757971380631715874187648296356201171875
  8 件のコメント
James Tursa
James Tursa 2022 年 11 月 15 日
The change in the background library code for Windows MATLAB was R2017b. Prior to that it displayed trailing 0s after about 16 digits, but from R2017b onwards it displays exact conversion when enough digits are requested. This is what motivated my num2strexact( ) FEX submission many years ago.
Walter Roberson
Walter Roberson 2022 年 11 月 15 日
@James Tursa thanks for the note!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by