Reputation: 112659
Try this in Matlab R2015b:
>> sprintf('%i\n',uint64(2)^62)
ans =
4611686018427387904 %// correct
>> sprintf('%i\n',uint64(2)^63)
ans =
9.223372e+18 %// why scientific notation?
In R2010b it's worse: a number as low as uint64(2)^31
already causes this behaviour:
>> sprintf('%i\n',uint64(2)^31)
ans =
2.147484e+009
Why does sprintf
use scientific notation with the '%i'
or '%d'
format specifiers? Can this be avoided?
Using num2str
instead of sprintf
is not a solution for me. Even though it does avoid scientific notation,
>> num2str(uint64(2)^63)
ans =
9223372036854775808 %// correct
I need to use sprintf
because num2str
doesn't support the "leading spaces" format specifier:
>> sprintf('% 25i\n',uint64(2)^62, uint64(2)^50)
ans =
4611686018427387904
1125899906842624 %// correct: leading spaces to give 25 characters for each number
>> num2str([uint64(2)^62;uint64(2)^50], '% 25i\n')
ans =
4611686018427387904
1125899906842624 %// incorrect: no leading spaces
>> num2str(uint64(2)^50, '% 25i\n')
ans =
1125899906842624 %// incorrect: no leading spaces
Upvotes: 1
Views: 302
Reputation: 24159
Looking at this question, it seems that MATLAB, for some reason (possibly because it's expecting a signed integer from %i
but you're giving it an unsigned one), treats the very-big-number (2^63) as a float
, and converts it to scientific notation which is also why if you write sprintf('%.18i\n',bitshift(uint64(2),62))
you end up losing precision:
9.223372036854775800e+18 vs. 9223372036854775808
Using %u
as opposed to %i
seems to produce the correct result:
sprintf('%u\n',bitshift(uint64(2),62))
ans =
9223372036854775808
(It makes more sense to use bitshift
in this specific scenario)
Upvotes: 2