Display decimal places of a variable using sprintf in MATLAB

I do not understand the following, what happens with the sprintf command.

>> vpa(exp(1),53) ans = 2.7182818284590455348848081484902650117874145507812500 >> e = 2.7182818284590455348848081484902650117874145507812500 e = 2.7183 >> sprintf('%0.53f', e) ans = 2.71828182845904550000000000000000000000000000000000000 

Why does sprintf show me the number e rounded, not the number, and I kept it in the first place?

+6
variables decimal printf matlab
Nov 19 '10 at 5:07
source share
1 answer

Double precision variables are default in MATLAB, so the variable e you create is limited by the precision of the double, which is about 16 digits. Even if you enter more digits, the double does not have the precision to accurately represent all these extra digits and round to the nearest number that it can represent.

EDIT: As explained in more detail by Andrew Janke in the answer to this follow-up question I posted, the number you chose for e is just the exact decimal extension of the binary value. In other words, this is a precisely representable value with which a close floating point number will be rounded. However, in this case, nothing more than approximately 16 digits after the decimal point is not considered significant, since it cannot be accurately represented using the double-precision type. Therefore, functions like SPRINTF automatically ignore these small values, instead print zeros.

+5
Nov 19 '10 at 5:10
source share



All Articles