how can i aproximate /modify long numbers

3 views (last 30 days)
a=2.65987 b=abs(2.6599-2.65987) which equals 3.0000-e05 ,after using fprintf('%0.7f\n',Eabs) i got 0.0000300
how can i get from 0.0000300 to 0.0000299 ? i also tried the round command didn't receive the desired value , also if i want to modify again let's say 2.6599 into 2.6598 after using the fprintf('%0.5g\n',a) command on the original value to how do i do it ? . I'm a BEGINNER in matlab ,i'd very much appreciate more than 1 solution (if possible and if i'm not asking for too much ) for learning purposes :) ,after browsing the mathworks website i've found that in the fprintf command i can put either f or g letters ,are there other combinations of the fprintf command ? or other letters ,if so what do they do ?

Accepted Answer

John D'Errico
John D'Errico on 29 Oct 2020
Edited: John D'Errico on 29 Oct 2020
It looks like you really need to understand floating point numbers.
a = 3.0000e-05
It looks like 3e-5. But is it? Changing the display format in MATLAb will do a lot, to see something closer to the number stored in MATLAB.
format long g
a =
As you can see, the number stored in MATLAB is not exactly 3e-5. But only close. Part of the problem is that MATLAB did not truly use the original numbers.
ans = '2.6598999999999999310773546312702819705009460449218750000'
ans = '2.6598700000000001786304437700891867280006408691406250000'
Neither number is exactly representable as a double precision number, just like 1/3 or 2/3 are not representable as a decimal number in a finite number of digits. So the difference of those two numbers will also be something that is not exactly what you think.
Numbers in MATLAB (at least those represented as doubles) are stored using a binary representation based on 52 bits of precision. And almost all decimal fractions cannot be represented in a finite number of binary bits.
NEVER trust the least significant digits of a floating point number, at least, not until you understand what numbers can be represented exactly, and the storage methods employed to encode them in MATLAB.
Of course, you could have used symbolic arithmetic to perform those computations in a better way.
a = 
Done in a symbolic form here, where the numbers are stored in an exact decimal form, MATLAB was albe to return the exact result. But be careful, as the next computation is very different.
a = 
The difference arises because the numbers are passed to sym as doubles, so they are not exactly stored.
So part of your problem lies in not understanding floating point numbers. But the rest of it, to see more digits of the number can be done either with the format command, or by a better use of tools like fprintf or sprintf. And for that, you would be best served just to read the help docs for sprintf and fprintf.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by