我正在尝试创建一个 while 循环来近似 cos(x) 的值,使其在 - 或 + 1-e10 范围内

问题描述 投票:0回答:2

我们必须使用 while 循环来解决这个问题(将 cos 的值近似到 - 或 + 1-e10 范围内),我相信我已经有了所有正确的设置,但我不断收到错误“缺少 TRUE/FALSE 需要的值”

问题陈述

函数的泰勒展开是将函数表示为无限项之和。我们可以通过取无穷和的前几项来近似该函数。我们包含的项越多,我们的近似值就越好。

余弦函数$cos(x)$的泰勒展开式为: 1-((x^2)/(2!))+(x^4)/(4!)...

x = pi/2
n = 0
approximation = 1
limit = 1e-10
while(approximation < (limit*(-1)) || approximation > limit){
  (term = c(((-1)^n)*((x)^(2*n)))/factorial(2*n))
  (n  = n + 1)
  (approximation = approximation + term)
}
approximation

这是我尝试过的代码,但就像我说的那样,它一直给我上述错误。

r while-loop approximation
2个回答
0
投票

诊断如下:当

n
达到
786
时,你的
term
的分子
((-1)^n)*((x)^(2*n))
Inf
无穷大处达到最大值。

n <- 785
((-1)^n)*((x)^(2*n))
#> [1] -8.094815e+307

n <- 786
((-1)^n)*((x)^(2*n))
#> Inf

现在,自从

factorial(2*n)
达到
Inf
以来,您的分母
n
已经是
86
一段时间了。

n <- 85
factorial(2*n)
#> [1] 7.257416e+306

n <- 86
factorial(2*n)
#> [1] Inf

所以到目前为止,总商是

0
:一个有限数除以
Inf
inity。但是当
n
达到
786
时,你的
term
就变成了
Inf / Inf
,即
NaN
:“不是数字”。

n <- 785
c(((-1)^n)*((x)^(2*n)))/factorial(2*n)
#> [1] 0
-8.094815e+307 / Inf
#> [1] 0

n <- 786
c(((-1)^n)*((x)^(2*n)))/factorial(2*n)
#> [1] NaN
Inf / Inf
#> [1] NaN

approximation
增加
NaN
时,结果仍然是
NaN

0 + NaN
#> [1] NaN

approximation
NaN
时,您的
while
条件评估为
NA
...

limit <- 1e-10

NaN < (limit*(-1))
#> [1] NA
NaN > limit
#> [1] NA

NA || NA
#> [1] NA

...这会产生您遇到的错误。

while(NA){
  # ...
}
#> Error in while (NA) { : missing value where TRUE/FALSE needed

0
投票

使用对数计算阶乘和

x
的幂,然后反转对数。

x <- pi/2
n <- 1
approximation <- 1
limit <- 1e-10
while(abs(approximation) > limit){
  lterm <- 2*n*log(x) - lfactorial(2*n)
  term <- (-1)^n * exp(lterm)
  approximation <- approximation + term
  n <- n + 1L
}
approximation
#> [1] -6.513362e-11

创建于 2024-01-31,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.