How to replace last 3 digits in a floating point number by another 3 digits

3 ビュー (過去 30 日間)
Abdul Gaffar
Abdul Gaffar 2019 年 12 月 4 日
コメント済み: Stephan 2019 年 12 月 5 日
Let
x = -3.141592653589793;
a = 287;
then how can I replace last 3 digits of x i.e. 793 by a ?

採用された回答

Stephan
Stephan 2019 年 12 月 5 日
編集済み: Stephan 2019 年 12 月 5 日
format long
x = -3.141592653589793;
a = 287;
x_new = sprintf('%.15f',x);
x_new(end-2:end) = (sprintf('%d',a));
x_new = str2double(x_new)
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 12 月 5 日
x_new =
-3.14159265358929
Notice the last three digits displayed are 929 . Tis is the 9793 changed to 9287 and then rounded to one place shorter, 929 . MATLAB displays one fewer digits than the available precision:
>> fprintf('%.999g\n', x_new)
-3.1415926535892868542987343971617519855499267578125
NOtice this is 9_286_8 rather than 9_287 as that is the closest you can represent in binary floating point double for that magnitude of number. It is not able to achive 9_287 exactly but it is able to achieve something that rounds to that.
You might even prefer
>> fprintf('%.999g\n', x_new*(1+eps))
-3.14159265358928774247715409728698432445526123046875
which is 9_287_7 which rounds to 9_288 but at least has the 9_287 in it.
You should be giving up on the idea of replacing "last" digits in a binary floating point number.
Perhaps you should be considering using symbolic numbers, which are better at approximating decimal. (It is possible to prove that they are not truely decimal either though.)
Stephan
Stephan 2019 年 12 月 5 日
Thank you for the insight.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 12 月 5 日
>> fprintf('%.999g\n', -3.141592653589793)
-3.141592653589793115997963468544185161590576171875
The last 3 digits of x are 875 not 393 .
MATLAB does not store numbers in decimal; it stores them in IEEE 754 Double Precision. It is not possible to exactly represent 1/10 in any finite number system based upon powers of 2, for exactly the same reason that you cannot exactly represent 1/7 in any file number system based upon powers of 10.

カテゴリ

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