在 R 中重复循环以计算 2.345 的余弦,精确到小数点后 5 位

repeat loop in R to compute the cosine of 2.345 correct to 5 decimal places

我想使用泰勒级数计算 2.345 的余弦,精确到小数点后 5 位。 我的代码如下。我不确定那有什么问题。 感谢您的帮助!

> x<-2.345
> count<-0
> repeat{
+ count<-count+1
+ initial = (-1)^(n-1)
+ numerator = x^(2*(n-1))
+ denominator = factorial(2*(n-1))
+ total=(initial*numerator)/denominator
+ if(abs((cos(x)-total)/cos(x))*100 <= 0.00001) break
+ sum=sum+total
+ }

只需更正代码中的错误即可。

x <- 2.345
n <- 0
Sum <- 0
repeat{
  n <- n + 1
  initial <- (-1)^(n - 1)
  numerator <- x^(2*(n - 1))
  denominator <- factorial(2*(n - 1))
  total <- (initial*numerator)/denominator
  Sum <- Sum + total
  if(abs((cos(x) - Sum)/cos(x))*100 < 0.00001) break
}

Sum
#[1] -0.699147
cos(x)
#[1] -0.6991469