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

与世无争的帅哥 提交于 2019-12-11 19:03:16

问题


I want to compute the cosine of 2.345 correct to 5 decimal places using Taylor series. My code is given below. I am not sure what is wrong with that. Any help is appreciated!

> 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
+ }

回答1:


It's a simple matter of correcting what is wrong in your code.

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


来源:https://stackoverflow.com/questions/54970790/repeat-loop-in-r-to-compute-the-cosine-of-2-345-correct-to-5-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!