Tutorial A11

1 Write a function that takes three vectors \(\mathbf{a}\), \(\mathbf{b}\), \(\mathbf{c}\) in 2D (NumPy arrays) and checks whether they form a triangle, i.e. if \(a + b = \pm c\).

2 Consider the vector \(\mathbf{v} = \begin{pmatrix}0& 0& 1\end{pmatrix}^\mathrm{T}\) and the rotation matrix

\begin{equation*} \mathbf{R} = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & -1\\ 0 & 1 & 0 \end{pmatrix} \end{equation*}

  • Rotate \(\mathbf{v}\) by \(\mathbf{R}\) to obtain \(\mathbf{v}^\prime\)

  • Compute the scalar product of \(\mathbf{v}\) and \(\mathbf{v}^\prime\)

  • By which angle did we rotate along which axis?

3 Consider the second Laplace spherical harmonic

\[Y_1^{-1}(\theta, \phi) = \frac{1}{2}\sqrt{\frac{3}{2\pi}}\sin\theta\mathrm{e}^{-i\phi}\]
  • Compute \(Y\) on a grid of 10 points per dimension (\(0 \leq \theta \leq \pi\), \(0 \leq \phi < 2\pi\)).

4 Given 1000 randomly places points in 2D, compute all the pairwise distances according to the formula below (see example below on how to generate random numbers).

\(d_{ij} = \sqrt{(x_i-x_j)^2+(y_i-y_j)^2}\) with \(i, j \in (1,2,...,1000)\)

Use three different Methods for this and compare the times (see example below on how to stop the time in Python):

  • a) A naive double for loop

  • Advanced b) A vectorized version using meshgrids

  • Advanced c) Outer subtraction

  • Advanced d) The cdist function from the scipy module (scipy.spatial.distance.cdist)

How many distances are larger than 0.5?

[1]:
# How to generate random numbers in NumPy
import numpy as np

x = np.random.random(1000)
# Gives you 1000 numbers in the half-open interval [0., 1.)
[2]:
# Example on how to measure execution times

import time
# Import the time module from the standard library

t0 = time.time()
# Store the current system time

print("Doing ...")
time.sleep(1)
# do something (or do nothing)

print("... stuff ...")
time.sleep(1)

t = time.time() - t0
# Get the current system time again and compute the ellapsed time

print(f"Total execution time: {t:.4f} seconds")
Doing ...
... stuff ...
Total execution time: 2.0033 seconds