首页 > 解决方案 > 乘法时R十进制精度发生变化

问题描述

R中的精度问题

当我在 R 中乘以高精度双值数字时,精度似乎发生了变化或发生了一些奇怪的事情。查看最后 4 位数字。

x <- 1608781598.186771296
y<-1000000000.00
print(x*y)
#1608781598186771456

#turns out that R is converting the precision like so
print(as.double(1608781598.186771296),digits=19)
#1608781598.186771393
#if I use the above value and multiply by a billion I can reproduce the incorrect value
print(1608781598.186771393*1000000000.0)
#1608781598186771456

python中的类似问题

事实上,类似的事情也在 Python 中发生

import numpy as np
print("{:.0f}".format(np.float128(1608781598.186771296)*np.float128(1000000000)))
#1608781598186771456

而我期望的值为 160878159818677 1296。这到底是怎么回事?

标签: pythonrdoubleprecision

解决方案


在 R 中,每个双精度值或十进制值都精确到 16 位有效数字。您的“x”有超过 16 个有效数字,因此在存储时已经对“x”变量进行了四舍五入。因此出现差异。


推荐阅读