Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Peterstone Avatar asked Nov 19 '10 05:11

Peterstone


People also ask

How do you get 2 decimal places in MATLAB?

For example, to display exactly 2 decimal digits of pi (and no trailing zeros), use sprintf("%. 2f",pi) .

What does %f do in MATLAB?

For example, %f converts floating-point values to text using fixed-point notation. Adjust the format by adding information to the operator, such as %. 2f to represent two digits after the decimal mark, or %12f to represent 12 characters in the output, padding with spaces as needed.


1 Answers

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.

like image 97
gnovice Avatar answered Nov 02 '22 21:11

gnovice