Challenge exercises#

Challenge exercise 1#

Let’s practice these plotting skills by making some further plots from a set of sunspot data.

  1. Download the datafile sunspot.month.csv from Moodle and upload it to the same directory in which this notebook is running. The data is read in using the supplied code below.

  2. Plot the number of sunspots as a function of time. Make sure the plot is properly labelled.

  3. Add Poisson counting error bars to the y-values. (Poisson counting error bars are simply +/-sqrt N).

  4. Limit the extent of your axes to 30 years for an interval of your choice.

  5. Save this plot.

  6. Create a histogram of the number of sunspots

  7. Label etc. the plot as needed

  8. Save this plot as well.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed
# We read in the data using the pandas module.
# This could have been read using the File object and techniques shown earlier ... And in fact that's what pandas
# will do internally, but if someone else has already provided a good solution its often good to just use it.

import pandas as pd
dat1 = pd.read_csv('sunspot.month.csv')
#What does the following line of code do? Make a note of this.
print(dat1.head(5))

# We need time and number of sunspots
year = dat1['time']
number_of_sunspots = dat1['number']
   entry         time  number
0      1  1749.000000    58.0
1      2  1749.083333    62.6
2      3  1749.166667    70.0
3      4  1749.250000    55.7
4      5  1749.333333    85.0

Challenge exercise 2#

The Taylor series expansion for the function \(f(x) = e^x\) is an \(n^{th}\) order polynomial that approximates \(f(x) = e^{x}\) for a given value of \(x\). In this exercise, you will visualise how this approximation improves the more terms you add to the Taylor Series expansion. This exercise makes use of functions and for loops.

The Taylor series for \(f(x) = e^{x}\) is:

\[e^{x} \approx \sum^{\infty}_{n=0}\frac{x^{n}}{n!} = 1+x+\frac{x^{2}}{2!} + \frac{x^{3}}{3!} + \frac{x^{4}}{4!} + \frac{x^{5}}{5!} + \cdots\]
  1. Write a function n_factorial that computes the factorial of any positive integer. This should take a single integer \(m\) as an input, and return \(m!\) You may need the result \(0! = 1\).

  2. Write a function approx_e that takes a value of x and the order \(n\) of the polynomial used to approximate \(f(x) = e^{x}\). The function should return an approximation of \(f(x) = e^x\) computed using a Taylor series expansion.

  3. Produce a plot of \(f(x) = e^{x}\) for values of \(x\) between 0 and 3. You should calculate \(e^{x}\) using np.exp(). np.exp(2) finds \(e^{2}\).

  4. Using your functions, plot the Taylor series approximations of \(f(x) = e^{x}\) for \(3^{rd}\), \(5^{th}\) and \(7^{th}\) order polynomial approximations on the same set of axes. Be sure to include a legend to identify each approximation plotted.

  5. Save the resulting plot.