# Tutorial for Homework 5 - Interference of Light


```python
# setup by importing some good modules
import sympy as sp
# All calls to sympy require sp. at the beginning
# One could use "from sympy import *", but then it's difficult to know what is sympy
# and what is another module when importing multiple modules.
# print things all pretty
from sympy.abc import *
sp.init_printing(use_latex='mathjax')

```

The sympy module (http://docs.sympy.org) allows one to plot functions without having to digitize the independent variable. Let's take a look at how to use it to plot functions. In the first example, we'll plot cosine, sine, and both together. These functions are built into sympy.  Simply give it the range of x-axis values you want plotted. NOTE: The text in between \$ is LaTeX typesetting.


```python
sp.plot(sp.cos(x), (x,-sp.pi, sp.pi), legend=True, line_color='red', xlabel='$\\theta$', ylabel='Amplitude')
sp.plot(sp.sin(x), (x,-sp.pi, sp.pi), legend=True, line_color='blue', xlabel='$\\theta$', ylabel='Amplitude')
sp.plot(sp.sin(x), sp.cos(x), (x,-sp.pi, sp.pi), legend=True, line_color='red', xlabel='$\\theta$', ylabel='Amplitude')
```

As you can see, once we plot two functions, we lose the ability to decorate them individually. Let's see how we can decorate them individually. To do this we'll need to make the graph an object and show the graph after we decorate it.


```python
#Define the graph as an object p
p = sp.plot(sp.sin(x), sp.cos(x), (x,-sp.pi, sp.pi), show=False, legend=True, xlabel='$\\theta$', ylabel='Amplitude')
p[0].line_color='red' #color the first data element as red
p[1].line_color='blue'#color the second data element as blue
p.show()
```

### Your turn
Using the cell below, try plotting $\cos^2(x)$ and $\sin^2(x)$ on the same graph. HINT: Squaring in Python is done with ```**2```. Make the cosine function purple and the sine function orange.


```python

```

## Diffraction

Now, let's look at a function that is relevant to our homework. The intensity pattern of light diffracting through a single slit is

$$I = I_o \left[\frac{\sin \left(\beta\right)}{\beta}\right]^2$$

To simplify the plotting, we'll define $\beta$ to be our $x$ variable. We will need to create this function since it does not exist in Sympy. We need to define the variables we plan to use as "symbols" for the independent and dependent variables. Once we define them, SymPy will also format them to look like pretty mathematics.


```python
#Define x and I as real-valued symbols
x, I= symbols("x, I", real = True)
# Define I
I = (sp.sin(x)/x)**2
I # This causes it to output formatted nicely. The print command formats it as computer code
```




$$\frac{1}{x^{2}} \sin^{2}{\left (x \right )}$$




```python
#Plot the intensity of diffraction from -10 to 10
sp.plot(I, (x,-10, 10))
```

### Your turn
In the cell below, plot the same diffraction data as above but label the axes with "Intensity" and "$\theta$".


```python

```

From the plot of the diffraction intensity function, we know the intensity equation must have a maximum in the center, i.e., when $\beta\rightarrow0$. L'H$\hat{\rm{o}}$pital's rule says

$$\lim_{\beta\to 0} \frac{\sin\beta}{\beta} = 1$$

We could also take a derivative if the intensity function and find the maximum. More on that later. We get the central maximum at $\beta=0$ since the limit is 1, the intensity is $I_o$ at $\beta = 0$. We read in the textbook that there is a first order minimum when 

$$D \sin\left(\theta\right) = m\lambda$$

and $m=1$. Minima will occur when $\beta = m\pi$ in the intensity equation above because $\sin(m\pi)=0$. Rearrarange the destructive interference condition equation above to solve for $m$; multiply by $\pi$ and substitute this into the first equation for $\beta$.

You should get

$$I = I_o \left[\frac{\sin \left(\frac{\pi D\sin\left(\theta\right)}{\lambda}\right)}{\frac{\pi D\sin\left(\theta\right)}{\lambda}}\right]^2$$

This means, we can determine the size of the single slit if we know the wavelength of light we are using. You did this in lab. Let's make a plot of this function by first defining $D=\lambda$ and $\lambda=500$ nm. Recall that $\sin\left(\theta\right)\approx\frac{y}{L}$, where $y$ is the distance away from the central point on the screen, and $L$ is the distance the screen is from the diffraction slit. You should also define $L = 1$ meter.

### Your turn
Below, edit the code to set the known variables and to create the function of diffraction intensity. Then, in the cell below the next one, plot the intensity function. Be sure to decorate your graph with axis labels and colors.


```python
#Create your constants
wl=0 #variable for wavelength
D=0 #variable for slit width
L=0 #variable for screen distance from slit
#Define x and I as real-valued symbols
x, I= symbols("x, I", real = True)
# Define I for real
I = x
I # This causes it to output formatted nicely. The print command formats it as computer code
```




$$x$$




```python
#Plot your intensity function
```

Try changing the wavelength. What happens to the diffraction pattern when $D\gt\lambda$? What happens to the diffraction pattern when $D\lt\lambda$?

## Interference

Next, let's look at interference. We expect interference to have constructive maxima following the relationship

$$d \sin\left(\theta\right) = m\lambda$$

The angle $\theta$ is the same as for diffraction. It is the angle away from a straight traveling beam. In this case $d$ is the spacing between two slits. From this pattern of constructive interference, we get a bright spot when $\theta=0$ and again when $\sin\left(\theta\right) = \lambda$. This means we'll get a bright spot on the screen when

$$\sin\left(\theta\right) \approx \frac{y}{L} = \frac{m\lambda}{d}$$

$$y = \frac{mL\lambda}{d}$$

Thus, we expect repeated constructive interference bright spots every integer multiple of

$$\frac{L\lambda}{d}$$

Since the interference has a bright spot when $\theta = 0$, we can write the intensity function as a cosine. There will be high intensity at the same locations as the conditional equation $d \sin\left(\theta\right) = m\lambda$. We know the cosine function should be maximum (have an argument of $m\pi$) at these locations. We also know that intensity is the square of the electric field of the light. This means the cosine function will be squared. This prevents a negative intensity, which makes no sense.

$$I = I_o \cos^2\left(\alpha\right)$$

Similar to the diffraction arguments, the angle $\alpha = m\pi$ is constructive interference. This gives

$$\alpha = \frac{\pi d \sin\left(\theta\right)}{\lambda}$$

### Your turn
In the cells below, plot the interference intensity function. You will need to define a value for $d$. Let's use $d = 1 \rm{\mu m}$. Be sure to give the function a new name, ```Iint``` for example. Once you get it to plot, try changing $d$ to values between $\lambda/2$ and $2\lambda$. What happens to the constructive interference fringes?


```python
#Define x and I as real-valued symbols
d = 1e-5 #double slit spacing
#wavelength is defined above already. You can redefine it anywhere with wl
# Define your symbols x and Iint
# Define interference intensity
Iint = sp.cos(sp.pi*d*x/500e-9/3)**2
Iint # This causes it to output formatted nicely. The print command formats it as computer code
```




$$\cos^{2}{\left (6.66666666666667 \pi x \right )}$$




```python
#Plot the intensity of an interference pattern.
sp.plot(Iint, (x, -0.5,0.5))
```

## Putting Diffraction and Interference Together
The combined effect of diffraction and interference is the product of the two functions. This gives

$$I = I_o \left[\frac{\sin \left(\frac{\pi D\sin\left(\theta\right)}{\lambda}\right)}{\frac{\pi D\sin\left(\theta\right)}{\lambda}}\right]^2 \cos^2\left(\frac{\pi d \sin\left(\theta\right)}{\lambda}\right)$$

### Your turn
Create a new function (give it a new name such as ```Itot```) for the combined diffraction and interference. Then, plot this function. Also plot the intensity function from diffraction. It should still be defined by ```I``` from above.

Test what happens when $D$ increases or decreases. Test what happens when $d$ increases or decreases. Test what happens when $\lambda$ increases or decreases.


```python
#Plot the combined diffraction and interference function along with the diffraction intensity function.
```

## Derivatives, Maxima, Minima
Another powerful tool in SymPy is its ability to calculate derivatives. It is really simple too! The command ```diff``` will calculate a derivative of any existing function. Below, I differentiate cosine and store it in the symbol dcos.


```python
dcos = sp.diff(sp.cos(x), x)
dcos
```




$$- \sin{\left (x \right )}$$



### Your turn
Try differentiating sine below.


```python

```

When it is a user defined function, the ```(x)``` is not necessary. Here is an example where I define a polynomial function related to the acceleration due to gravity and differentiate it to obtain the velocity function.


```python
t, poly = symbols("t, poly", real = True)
poly = 0.5*(-9.8)*t**2+20*t+1
dpoly = sp.diff(poly, t)
poly, dpoly
```




$$\left ( - 4.9 t^{2} + 20 t + 1, \quad - 9.8 t + 20\right )$$



I can solve for extrema too. To do this I use the SymPy ```solveset``` function. According to SymPy's documentation... The first argument for ```solveset()``` is an equation (equaled to zero by solveset) and the second argument is the symbol that we want to solve the equation for (usually your independent variable). Thus, ```solveset``` finds the roots of a function, i.e., where it is equal to zero.


```python
extrema = sp.solveset(dpoly, t) 
extrema
```




$$\left\{2.04081632653061\right\}$$



It's telling me there is a maximum or minimum at $t = 2.04$ seconds. We know this polynomial has no upper and lower limits. As $t\to\pm\infty$, the function goes to $\pm\infty$ depending on the concavity (2nd derivative). Let's plot ```poly``` to see if this extremum is true. First, I will find the zeros (where the function evaluates to zero) and plot over that range. This would correspond to an object going from the ground, upward to maximum height, and then back to the ground. Keep in mind my function implies I threw the object upward from a height of 1 meter.


```python
polyzeros = sp.solveset(poly, t)
polyzeros
```




$$\left\{-0.0494020618888763, 4.1310347149501\right\}$$




```python
sp.plot(poly, (t, -0.0494, 4.131))
```

It does appear that there is a maximum at $t=2.04$ seconds.

### Your turn
Find the derivative of your total intensity function. I have written the function below, but you should already have it defined above.


```python
#Define x and I as real-valued symbols
x, Itot = symbols("x, Itot", real=True)
L = 1
wl = 5e-7
D = 2e-7
dd = 1e-6 #double slit spacing
# Define your symbols x and Iint
# Define interference intensity
Itot = (sp.sin(sp.pi*D*x/(wl*L))/(sp.pi*D*x/(wl*L))*sp.cos(sp.pi*dd*x/(wl*L)))**2
Itot # This causes it to output formatted nicely. The print command formats it as computer code
```




$$\frac{6.25}{\pi^{2} x^{2}} \sin^{2}{\left (0.4 \pi x \right )} \cos^{2}{\left (2.0 \pi x \right )}$$




```python
sp.plot(Itot, (x, -5, 5))
```


```python
Itotdiff = sp.diff(x,x)
Itotdiff
```




$$1$$



Ouch! That is quite a derivative!!! We can try to find the roots using ```solveset```. Give it a shot. To limit the range that Python tries to search, use the argument ```sp.Interval```. NOTE: You'll need to change ```y``` to the appropriate function.


```python
Itotextreme = sp.solveset(y, x, sp.Interval(-0.1,0.1))
Itotextreme
```




$$\emptyset$$



The result is pretty difficult to interpret when the function is so complicated. Let's plot the derivative to see if we can find the global maximum and first two minima. To do this choose a range of x values to plot that will zoom in on the region of the total intensity where you expect these to be.


```python
sp.plot(x, (x,-1,1))
```

## Integrals
You don't have integrals on your homework, but we might as well look at how to evaluate them using SymPy while we are learning about SymPy.

To take the integral of a function is as simple as taking a derivative. The exception is that integrals can be definite or indefinite. Let's look at an example of both using SymPy's ```integrate``` function.

First, we'll take the indefinite integral of cosine.


```python
sp.integrate(sp.cos(x),x)
```




$$\sin{\left (x \right )}$$



Excellent! We could have stored that in a variable ```intcos = sp.integrate(sp.cos(x),x)``` if we wanted to use the integral later. Now, let's integrate over a range (definite integral). We'll continue with the cosine function. Before we do, let's think about what we expect to obtain from the integral. Say we integrate cosine from $-\pi$ to $\pi$. This is one period of cosine. What do you expect to get from the integral?


```python
sp.integrate(sp.cos(x),(x,-1, 1))
```




$$2 \sin{\left (1 \right )}$$



### Your turn
Create a function that describes a projectile's velocity as a function of time. Give the object an initial upward velocity of 10 m/s and downward acceleration due to gravity. Integrate this function to obtain the position vs. time function. First, do this as an indefinite integral. Then, integrate over the range of times that correspond to the object leaving the ground and reaching its maximum height. Do each of these in their own cell. You may want to plot your velocity and position functions to visually inspect that they are what you expect. After you obtain your results, create a markdown cell to explain the results at the bottom. Use LaTeX in your markdown to typeset the equations for velocity and position functions.


```python

```

d4c1d61d9a0597c67e0bb242547879ebf26d5a50
ipynb
Jupyter Notebook
HW5-Interference-Tutorial.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
HW5-Interference-Tutorial.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
2018-08-06T17:55:54.000Z
2018-08-07T18:47:52.000Z
HW5-Interference-Tutorial.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
2018-08-06T17:39:08.000Z
2018-08-06T17:39:08.000Z
Qwen/Qwen-72B
1. YES
2. YES