本文介绍了在R中重复循环以计算2.345的余弦,正确到小数点后5位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用泰勒级数将2.345的余弦值校正为5个小数位.我的代码如下.我不确定这有什么问题.感谢您的帮助!
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
+ }
推荐答案
纠正代码中的错误很简单.
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
这篇关于在R中重复循环以计算2.345的余弦,正确到小数点后5位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!