R_U*_*ser 16 r rounding-error numeric decimal
我DECIMAL从MySQL-Table中读取以格式存储的数据.我想对R内的那些数字进行计算.
我过去常常使用它们进行数字再现as.numeric(),但文档说:
numeric与double(和real)相同.
但是R中还有一个数据类型Decimal吗?(没有舍入错误的数据类型,...)
这里有一个舍入错误问题的简单示例:
numbersStrings = c("0.1", "0.9")
numbersNumeric = as.numeric(numbersStrings)
numbersMirror = c(numbersNumeric, 1-numbersNumeric)
str(numbersMirror)
numbersMirror
unique(numbersMirror) # has two times 0.1 ...
sprintf("%.25f", numbersMirror)
sprintf("%.25f", unique(numbersMirror)) # ... because there was a rounding error
Run Code Online (Sandbox Code Playgroud)
你可以创建自己的:
d <- structure( list(i=589L,exp=2L), class="decimal" )
print.decimal <- function( x, ...) print( x$i * 10^(-x$exp) )
> d
[1] 5.89
Run Code Online (Sandbox Code Playgroud)
实际上,一些大数字包也可能适用于此,因为它们使用类似的表示....
与 Ari 答案类似的方法,但使用包integer64中的类bit64。在各种本身不支持十进制类型的应用程序中,使用 big int 作为十进制的基础数据类型是常见的做法。
library(bit64)
as.decimal = function(x, p=2L) structure(as.integer64(x*10^p), class="decimal", precision=p)
print.decimal = function(x) print(as.double(x))
as.integer64.decimal = function(x) structure(x, class="integer64", precision=NULL) # this should not be exported
as.double.decimal = function(x) as.integer64(x)/(10^attr(x, "precision"))
is.decimal = function(x) inherits(x, "decimal")
"==.decimal" = function(e1, e2) `==`(as.integer64(e1), as.integer64(e2))
"+.decimal" = function(e1, e2) `+`(as.integer64(e1), as.integer64(e2))
d = as.decimal(12.69)
is.decimal(d)
#[1] TRUE
print(d)
#[1] 12.69
as.double(d)
#[1] 12.69
d + as.decimal(0.9)
#[1] 13.59
0.1 + 0.2 == 0.3
#[1] FALSE
as.decimal(0.1) + as.decimal(0.2) == as.decimal(0.3)
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)