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.
Solution
To avoid this error, simply initialize
n <- 1, which aligns your terms with the Taylor series.Diagnosis
When you initialize
n <- 0, the series starts with2rather than1, unlike the Taylor series. This causesapproximationto converge wrongly on1, by the 11th iteration.As discussed below, this loops out of control until throwing an error.
But with
n <- 1we properly obtain anapproximationof-6.51335680512735e-11, which terminates on the 7th iteration:Error
As shown above,
approximationconverges on1, and always remains greater than thelimitof1e-10. So the condition is alwaysTRUE, and thewhileloop continues indefinitely.But when
nreaches786, yourterm's numerator((-1)^n)*((x)^(2*n))maxes out atInfinity.Now your denominator
factorial(2*n)has beenInffor some time, ever sincenreached86.So until now, the overall quotient has been
0: a finite number divided byInfinity. But whennreaches786, yourtermbecomesInf / Inf, which isNaN: "Not a Number".When
approximationis incremented byNaN, the result is stillNaN.With an
approximationofNaN, yourwhileconditions evaluate toNA: "Not Available".In your
whileloop, thisNAcondition throws the error you encountered.