How to store only 3 digits after the decimal point?

660 ビュー (過去 30 日間)
Faez Alkadi
Faez Alkadi 2017 年 9 月 21 日
コメント済み: Faez Alkadi 2017 年 9 月 21 日
I'm working on R2016a and using round function to get red of the extra digits that I don't need on right side of the decimal point, so I did the following :
x=2.123456789123456789
y=round(x,3),
so I got:
y=2.123000000000000000
But I want it to be (stored) as:
y=2.123
Is what i'm doing write ?
Thank you so much.

採用された回答

Walter Roberson
Walter Roberson 2017 年 9 月 21 日
編集済み: Walter Roberson 2017 年 9 月 21 日
MATLAB uses IEEE 754 Binary Double Precision to represent floating point numbers. All floating point scheme that use binary mantissas cannot exactly represent 1/10, just like finite decimal representation schemes cannot exactly represent 1/3 or 1/7 .
IEEE 754 also defined a Decimal Double Precision representation scheme, which can represent 2.123 exactly. However, computing those values in software is much slower. The only systems I know of that implement IEEE 754 Decimal Double Precision in hardware are the IBM z90 series.
If you need a certain specific number of decimal places to be stored, then use rationals with a power-of-10 denominator.
  3 件のコメント
Walter Roberson
Walter Roberson 2017 年 9 月 21 日
No. IEEE 754 Binary Double Precision is able to exactly represent all integers in the range +/- 2^53, but for N digit decimal numbers, only 2^N out of 10^N can be exactly represented. For example, for 3 digits, 0.000, 0.125, 0.250, 0.375, 0.500, 0.625, 0.750, 0.875 -- only 8 exactly representable 3 digit decimals out of 1000.
2.123 is not exactly representable in IEEE 754 Binary Double Precision. The closest exactly representable number is 2.12300000000000022026824808563105762004852294921875
Faez Alkadi
Faez Alkadi 2017 年 9 月 21 日
Thank you !

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

その他の回答 (1 件)

James Tursa
James Tursa 2017 年 9 月 21 日
編集済み: James Tursa 2017 年 9 月 21 日
This is just a display difference. The numbers are the same. E.g.,
>> format long
>> x = 2.123456789123456789
x =
2.123456789123457
>> y = round(x,3)
y =
2.123000000000000
>> z = 2.123
z =
2.123000000000000
>> y == z
ans =
1
>> format short g
>> y
y =
2.123
>> z
z =
2.123
If you want to display the number to three decimal places, e.g.,
>> fprintf(' %.3f\n',y)
2.123
>> fprintf(' %.3f\n',z)
2.123
But keep in mind that 2.123 cannot be represented exactly in IEEE double precision format. The nearest IEEE double precision number to 2.123, converted to an exact decimal representation, is
>> num2strexact(2.123)
ans =
2.12300000000000022026824808563105762004852294921875

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by