We must use a while loop to solve this problem (approximating the value of cos to within - or + 1-e10 ) and I believe I have all the right setup but I keep getting the error "missing value where TRUE/FALSE needed"
The question stating
A Taylor expansion of a function is an expression of the function as an infinite sum of terms. We can approximate the function by taking the first several terms of the infinite sum. The more terms we include, the better will be our approximation.
The Taylor expansion of the cosine function $cos(x)$ is: 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
This is the code that I attempted but like I said it keeps giving me the error stated above.
Compute the factorial and the powers of x using logarithms, then invert the logs.
In the question's code, if n starts at zero then approximation is off by 1. The cosinus series expansion 1st term is 1 because (-1)^0 == 1.
So I start with n <- 1 and approximation <- 1. This avoids having to treat the first case as a special case. I also change the stop criterion to one based on differences of two consecutive values. This allows for the computation of cos(x) to be more general and not depend on the input x. In question's algorithm, only values with an approximate final value equal to zero were allowed.
As for the use of log factorials, the value of (2n)! grows rapidly and with a small enough allowed absolute error it would become Inf, and all next term's would be zero, resulting in an infinite loop. lfactorial keeps the numbers amenable and the intermediate calculations finite.
Speed is not important so I keep the repeated calculation of log(x) in the loop, to have the formula used as close to the Taylor series expansion formula as possible. This calculation can (and should) be made before the loop. And multiplied by 2, since we are at it.
taylor_cos <- function(x, limit = 1e-10) {
n <- 1
approximation <- 1
err <- Inf
while(err > limit){
lterm <- 2*n*log(x) - lfactorial(2*n)
term <- (-1)^n * exp(lterm)
previous <- approximation
approximation <- previous + term
err <- abs(previous - approximation)
n <- n + 1L
}
approximation
}
taylor_cos(pi/2)
#> [1] 5.260102e-13
taylor_cos(pi/3)
#> [1] 0.5
taylor_cos(pi/6)
#> [1] 0.8660254
taylor_cos(pi/4)
#> [1] 0.7071068
Created on 2024-01-31 with reprex v2.0.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With