【发布时间】:2023-02-08 17:48:38
【问题描述】:
下面的代码估计 R 中的 pi,现在我试图找到最少的项数 N_Min 你必须在你对馅饼的估计中包括在内,以使其精确到小数点后三位。
pi_Est<- function(NTerms){
NTerms = 5 # start with an estimate of just five terms
pi_Est = 0 # initialise the value of pi to zero
Sum_i = NA # initialise the summation variable to null
for(ii in 1:NTerms)
{
Sum_i[ii] = (-1)^(ii+1)/(2*ii - 1) # this is the series equation for calculating pi
}
Sum_i = 4*Sum_i # multiply by four as required in the formula (see lecture notes)
pi_Est = sum(Sum_i)
cat('\nThe estimate of pi with terms = ', NTerms ,' is ',pi_Est)
}
【问题讨论】:
-
如果你在函数内部设置
NTerms = 5,输入参数将被覆盖,你将始终得到NTerms = 5的结果。也许将其定义为默认值:pi_Est <- function(NTerms = 5){...}
标签: r