My boss just told me to write a cosine function. Being a good math geek, my mind immediately conjured the appropriate Taylor Series.
$$\cos(x) = \frac 1 {0!} - \frac {x^2} {2!} + \frac {x^4} {4!} - \frac {x^6} {6!} + \cdots + \frac{(-1)^k \times x^{2k}} {(2k)!} + \cdots$$
However, my boss is very picky. He would like to be able to specify exactly how many terms of the Taylor Series to compute. Can you help me write this function?
Your Task
Given a floating point value \$x\$ from \$0\$ to \$2\pi\$ and a positive integer \$n\$ less than \$100\$, compute the sum of the first \$n\$ terms of the Taylor series given above for \$\cos(x)\$.
This is code-golf, so shortest code wins. Input and output can be taken in any of the standard ways. Standard loopholes are forbidden.
Notes
- Input can be taken in any reasonable form, as long as there is a clear separation between \$x\$ and \$n\$.
- Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.
- If it makes sense for the language being used, computations may be done using exact rational quantities, but the input and output shall still be in decimal form.
Examples
x | n | Output
----+----+--------------
0.0 | 1 | 1.0
0.5 | 1 | 1.0
0.5 | 2 | 0.875
0.5 | 4 | 0.87758246...
0.5 | 9 | 0.87758256...
2.0 | 2 | -1.0
2.0 | 5 | -0.4158730...
n
is also greater than0
? \$\endgroup\$