how can i aproximate /modify long numbers
2 ビュー (過去 30 日間)
古いコメントを表示
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 ?
0 件のコメント
採用された回答
John D'Errico
2020 年 10 月 29 日
編集済み: John D'Errico
2020 年 10 月 29 日
It looks like you really need to understand floating point numbers.
a=abs(2.6599-2.65987)
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.
sprintf('%0.55f',2.6599)
sprintf('%0.55f',2.65987)
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=abs(sym('2.6599')-sym('2.65987'))
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=vpa(abs(sym(2.6599)-sym(2.65987)))
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!