使用R可以显示小数点后多少个数字?

时间:2021-05-17 17:11:46

I was wondering how far can you print this:

我想知道你能打印多久这个:

http://www.iheartchaos.com/post/16393143676/fun-with-math-dividing-one-by-998001-yields-a

http://www.iheartchaos.com/post/16393143676/fun-with-math-dividing-one-by-998001-yields-a

In R.

在R.

e.g: 1/998001

例如:1/998001

2 个解决方案

#1


16  

You could use the mpc package,

你可以使用mpc包,

# 3000 is the precision in bits
> mpc(1, 3000) / mpc(998001, 3000)
[1] "(1.0020030040050060070080 ...
...

#2


13  

Here is a solution that does not require any fancy packages, just base R and a flashback to elementary school arithmetic:

这是一个不需要任何花哨的软件包的解决方案,只需要基础R和小学算术的闪回:

longdiv <- function(num,den, limit=3000, spaces=TRUE) {
    i <- 0
    if( num < den ) {
        cat('0.')
        num <- num*10
    } else {
        cat( num %/% den, '.', sep='')
        num <- (num %% den) * 10
    }
    while( i < limit ) {
        i <- i + 1
        if( num < den ){
            cat('0')
            num <- num*10
        } else {
            cat( num %/% den )
            num <- (num %% den) * 10
        }
        if(spaces){
            if( (i %% 30) == 0 ) {
                cat('\n')
            } else if( (i %% 3) == 0 ) {
                cat(' ')
            }
        }
        flush.console()
    }
    cat('\n')
}   


longdiv(1,998001)

#1


16  

You could use the mpc package,

你可以使用mpc包,

# 3000 is the precision in bits
> mpc(1, 3000) / mpc(998001, 3000)
[1] "(1.0020030040050060070080 ...
...

#2


13  

Here is a solution that does not require any fancy packages, just base R and a flashback to elementary school arithmetic:

这是一个不需要任何花哨的软件包的解决方案,只需要基础R和小学算术的闪回:

longdiv <- function(num,den, limit=3000, spaces=TRUE) {
    i <- 0
    if( num < den ) {
        cat('0.')
        num <- num*10
    } else {
        cat( num %/% den, '.', sep='')
        num <- (num %% den) * 10
    }
    while( i < limit ) {
        i <- i + 1
        if( num < den ){
            cat('0')
            num <- num*10
        } else {
            cat( num %/% den )
            num <- (num %% den) * 10
        }
        if(spaces){
            if( (i %% 30) == 0 ) {
                cat('\n')
            } else if( (i %% 3) == 0 ) {
                cat(' ')
            }
        }
        flush.console()
    }
    cat('\n')
}   


longdiv(1,998001)