Exercise: Piecewise functions

Task: Write an efficient numpy-based code for computing the values of

$$ f(x) = \left\{ \begin{aligned} & x \sin(x^2) && \text{ if } x < 0, \\ & \cos(x)&& \text{ if } x \ge 0 \end{aligned} \right. $$

at 1000001 uniformly spaced points in the interval $[-5, 5]$. Time it and then plot the function.

In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline