R语言:计较分数的准确值
利用数组较准确计较M/N(0<M<N<=100)的值。假如M/N是无限轮回小数,则计较并输出它的第一轮回节,同时要求输出轮回的起止位置(小数位的序号)
frac <- function(m,n){
remainder <- numeric(100)
quotient <- numeric(100)
i <- 1
while(i <= 100) {
remainder[m] <- i
m <- m*10
quotient[i] <- m%/%n
m <- m%%n
i <- i+1
}
u <- sum(remainder != 0)
v <- paste(quotient[1:u], collapse = “”)
paste(paste( ‘0.’,v,sep = ”),u, sep = ‘/’ )
}
frac(16,19)
[1] “0.842105263157894736/18” #18位
frac(23,87)
[1] “0.2643678160919540229885057471/28” #28位
frac(16,113)
[1] “0.1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654/100” #100位
要是较量懒,就用现成的包,可以到任意精度。
library(Rmpfr);
mpfr(16, 300) / mpfr(19, 300);
1 ‘mpfr’ number of precision 300 bits
[1] 0.84210526315789473684210526315789473684210526315789473684210526315789473684210526315789473671