Peterstone
Peterstone

Reputation: 7449

Showing decimals of a variable with sprintf in MATLAB

I don't understand the next thing that happens using 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 instead of the number and I kept at the first place?

Upvotes: 6

Views: 1662

Answers (1)

gnovice
gnovice

Reputation: 125854

Variables are double precision by default in MATLAB, so the variable e that you create is limited to the precision of a double, which is about 16 digits. Even though you entered more digits, a double doesn't have the precision to accurately represent all those extra digits and rounds off to the nearest number it can represent.

EDIT: As explained in more detail by Andrew Janke in his answer to this follow-up question I posted, the number you chose for e just happens to be an exact decimal expansion of the binary value. In other words, it's the exactly-representable value that a nearby floating-point number would get rounded to. However, in this case anything more than approximately 16 digits past the decimal point is not considered significant since it can't really be represented accurately by a double-precision type. Therefore, functions like SPRINTF will automatically ignore these small values, printing zeroes instead.

Upvotes: 5

Related Questions