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

3 visualizzazioni (ultimi 30 giorni)
Let
x = -3.141592653589793;
a = 287;
then how can I replace last 3 digits of x i.e. 793 by a ?

Risposta accettata

Stephan
Stephan il 5 Dic 2019
Modificato: Stephan il 5 Dic 2019
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 Commenti
Walter Roberson
Walter Roberson il 5 Dic 2019
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.)

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 5 Dic 2019
>> 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.

Community Treasure Hunt

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

Start Hunting!

Translated by