让MATLAB打印完整的2 ^ 64值 [英] Have MATLAB print full 2^64 value
问题描述
我正在尝试打印值:
(2^32 - 1) * (2^32 - 1)
在MATLAB中显示所有20位数字.我已经尝试过
in MATLAB and have it display all 20 digits. I've tried
fomat long
和
sprintf('%20d',ans)
这些都没有得到我想要的结果并打印:
Neither of these are getting the results I want and print:
1.844674406511962e+19
或类似的东西.有什么建议吗?
or something to that effect. Any advice?
推荐答案
您应该期望%d
将整数打印为整数,不需要精度或字段宽度说明,而无需使用指数表示法(%e
). sprintf
无法将此整数显示为整数是有原因的.这就是原因(以及更多).
You are right to expect %d
to print an integer as an integer, requiring no precision or field width specification, rather than in exponential notation (%e
). There is a reason why sprintf
fails to display this integer as an integer. Here's why (and more).
根据 sprintf
文档,这是%d
指定的输出格式:
From the sprintf
documentation, this is the output format that %d
specifies:
整数,已签名;
%d
或%i
; 底数10
Integer, signed;
%d
or%i
; Base 10
此处的关键字是 signed .这个确实指定一个以十进制(以10为底)表示法打印的整数,但是占用一个位!您(和%d
)可以用 64位带符号整数(即 intmax('int64')
).并且由于(2^32 - 1) * (2^32 - 1) > 2^63-1
, sprintf
会退回到指数表示法(%e
).但是请不要相信我的话:
The keyword here is signed. This does specify an integer printed in decimal (base 10) notation, but the sign takes up one bit! The largest integer you (and %d
) can represent with a 64-bit signed integer (i.e. int64
) is 2^63-1
(check with intmax('int64')
). And since (2^32 - 1) * (2^32 - 1) > 2^63-1
, sprintf
falls back to exponential notation (%e
). But don't take my word for it:
>> sprintf('%d',uint64(2^63)-1)
ans =
9223372036854775807
>> sprintf('%d',uint64(2^63))
ans =
9.223372e+18
解决方案是使用 unsigned 整数格式:%u
.
>> sprintf('%u',uint64(2^63))
ans =
9223372036854775808
使用(2^32 - 1) * (2^32 - 1)
时,问题不太明显,但是解决方案是相同的:
With (2^32 - 1) * (2^32 - 1)
, the issue is less subtle, but the solution is the same:
>> val = (2^32 - 1) * (2^32 - 1); % > 2^63-1
>> sprintf('%u',val)
ans =
18446744065119617024
这回答了问题,但这仍然是错误.这次不是sprintf
的错.双精度(64位)浮点数只能表示整数最多2 ^ 53 而不会丢失精度 1 .由于MATLAB中的默认数据类型为double
,因此val
被存储为double
.为确保不损失精度,请使用uint64
类型:
This answers the question, but this is still wrong. This time it's not sprintf
's fault. Double precision (64-bit) floating point numbers can only represent integers up to 2^53 without loss of precision1. Since the default data type in MATLAB is double
, val
is stored as a double
. To ensure no loss of precision, use the uint64
type:
>> valUI = uint64(2^32 - 1) * uint64(2^32 - 1)
>> sprintf('%u',valUI)
ans =
18446744065119617025
关闭. double
几乎很幸运.
1 此值2 ^ 53(或9,007,199,254,740,992)可以通过 flintmax('double')
.
1This value of 2^53 (or 9,007,199,254,740,992) can be verified by flintmax('double')
.
这篇关于让MATLAB打印完整的2 ^ 64值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!