To translate the cosine formula into code, let's look first at the individual terms in series. Each term can be written as:
with n going from zero to infinity. We can code this term in python as:
Suppose we just wanted to add up the first four terms. The series would look like this:
Notice that this series only goes up to 4, not infinity, so it does not give us the exact value of the cosine. We can translate this sum into code like this:
The limit parameter tells us the upper limit of n. So, for example, to approximate the cosine of 1 with the first four terms, we call the cosine function like this:
This is a pretty good approximation, but the mathematical formula for the cosine goes from n to infinity. How do we code that? Keep in mind that computers don't have an infinite amount of storage space. The best we can do is arrive at an answer that fits on our computer and is accurate enough for our purposes.
Even the cos function in Python's math module can only give an approximation:
You can see that we already have a pretty good approximation of the cos function (at least when trying to get the cosine of 1). Let's see if we can do better.
When we looked at the power series for cosine, we saw that the exact value of the cosine is always between two consecutive partial sums. Specifically, we saw that
Suppose that we can tolerate an error of EPSILON, where EPSILON has the value 0.0000000000000001 (the acceptable error may vary depending on the application). Instead of a for loop, we use a while loop to compare each term with the next until we get two terms with a difference of less than EPSILON and then leave the loop. In this way, we can say that our function has an error bound of EPSILON.
This gives us a better approximation of the cosine of 1:
1 2 3 4 5 6 7 8 9 10 11 12