Assignment 3

Important dates

Assigned15 Jun 2018 @ 10:05h
Due22 Jun 2018 @ 23:59h

Description

Implement a Taylor series approximation of some mathematical functions.

In mathematics, the Taylor series is a way of approximating transcendental functions such as $\sin x$ or $\log x$. In this approach, we can approximate a mathematical function as closely as we might want to by adding together numbers that get us closer and closer to the true value of the function. For example, the exponential function $e^x$ can be approximated as:

\[ e^x = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots = \sum_{n=0}^{\infty} \frac{x^n}{n!} \]

and the $\sin$ function can be approximated as:

\[ \sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} \]

The more terms we include in our approximation, the better an approximation we get of $\sin x$. In this assignment, you must implement Taylor series approximations for these two functions. Your functions should take two parameters: the value of $x$ and the number of terms to use in the approximation:

/**
 * Calculate an approximate value for the exponential function.
 *
 * @param   x     the value to raise e to the power of (i.e., e to the x)
 * @param   terms the number of Taylor series terms to use in the approximation
 *                @pre terms > 0
 */
double approxExp(double x, int terms);

/**
 * Calculate an approximate value for the sine function.
 *
 * @param   x     the value to calculate the sine of
 * @param   terms the number of Taylor series terms to use in the approximation
 *                @pre terms > 0
 */
double approxSine(double x, int terms);

For example, when my test code calls approxExp(2.2, 4), you should return the sum of the first four terms of the $e^x$ approximation, i.e.:

\[ 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} = 1 + (2.2) + \frac{(2.2)^2}{2!} + \frac{(2.2)^3}{3!} = 1 + 2.2 + 2.42 + 1.77467 = 7.394667 \]

If my test code calls approxSin(3.14, 3), you should return the sum of the first three terms of the $\sin x$ approximation, i.e.:

\[ x - \frac{x^3}{3!} + \frac{x^5}{5!} = 3.14 - \frac{(3.14)^3}{3!} + \frac{(3.14)^5}{120} = 3.14 - \frac{30.959}{6} + \frac{305.245}{120} = 0.523875 \]

My test will include these test values, so yours should too.

As always, assignments in this course must be done individually. You can (and are encouraged to!) work together on exercises, but you must do the assignments yourself. If in doubt, come and talk with me.