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?
For example, to display exactly 2 decimal digits of pi (and no trailing zeros), use sprintf("%. 2f",pi) .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With