6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peterstone
  • 7,119
  • 14
  • 41
  • 49

1 Answers1

5

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.

Community
  • 1
  • 1
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • 1
    you skipped a step: When using sprintf, e is implicitly converted to a double. Variables are ... – Marc Nov 19 '10 at 14:58
  • 1
    @Marc: Hm? Here, e is already a double because it's initialized from a literal due to the copy and pasting. In Matlab, all numeric literals produce double values. You can confirm it with "class(2.7182818284590455348848081484902650117874145507812500)", which returns 'double'. class(exp(1)) is double, too. Most of the displayed digits are bogus because they're beyond double's limit of precision; vpa() just doesn't zero them out like printf() does. – Andrew Janke Nov 19 '10 at 17:16