{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Introduction to Computational Physics Lab\n",
"\n",
"*name*: ____________ \n",
"\n",
"This is a *Jupyter Notebook*. It is organized in \"cells\", some containing\n",
"Python code (those labelled with `[]:`) and others containing text (such as this one).\n",
"\n",
"When you start this file with Jupyter, you can edit and execute the code\n",
"blocks. Click in a code block, type or edit some code, then type `Shift-Enter`\n",
"to execute the code. You can also edit text blocks like this one; type\n",
"`Shift-Enter` to render the text after editing. If the address of this page in\n",
"your browser ends in `.html` then you are viewing a static rendering of the\n",
"notebook and you will not be able to edit it.\n",
"\n",
"To complete this lab, you must\n",
"\n",
"1. **Get Jupyter running**. \n",
" See [How to Get Started with the Jupyter Notebook][getting_started].\n",
"1. **Download the code files** and save them in a folder where you plan \n",
" to do your computational work this semester. \n",
" The files may be found on the lab web page. \n",
"1. **Type your name** in the text block at the top of this document. \n",
" (Double-click the block to open it for editing.)\n",
"1. **Read through** this entire notebook to see how it's organized.\n",
"1. **Execute the import lines** without error. \n",
"1. **Answer every \"Question\" in B. Exercises** by writing and executing the\n",
" appropriate code. That section starts with \"Example 1\" and \"Question 1\". You\n",
" can answer the \"Question 1\" by following the model in the \"Example 1\".\n",
" Repeat for all Questions.\n",
"1. *Section C. Importing Packages* is optional.\n",
"1. **Study the methods illustrated in D. Vector Sum Example**.\n",
"1. **Answer all the E. Vector Problems** as directed by writing and executing\n",
" the code required.\n",
"1. **Save this notebook as a .ipynb file and submit it** on the course web page\n",
" when the is lab due.\n",
"\n",
"[getting_started]: https://madisoncollegephysics.net/comp/getting_started.html\n",
"\n",
"------------\n",
"\n",
"## A. Set Up\n",
"\n",
"To be able to execute much of the code we use, you will need to first execute\n",
"these two `import` statements.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"from numpy import *\n",
"import scipy.constants"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"The [NumPy](https://numpy.org/) package (short for *numerical python*)\n",
"will allow you to use vectors, trig functions and much more.\n",
"\n",
"The [`scipy.constants`](https://docs.scipy.org/doc/scipy/reference/constants.html) \n",
"package contains a lot of constants and unit conversion values. \n",
"The [SciPy](https://scipy.org/) package (short for *scientific python*)\n",
"contains many advanced computational physics libraries.\n",
"\n",
"## B. Exercises\n",
"\n",
"Below are a series of examples, each followed by a similar question. \n",
"Copy the example code and paste it into the question's answer cell. \n",
"Then edit as needed to answer the question.\n",
"\n",
"### Example 1\n",
"\n",
"Mt. Everest is 29 000 ft high. How many meters is that?\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"h_ft = 29000\n",
"h_m = h_ft * scipy.constants.foot\n",
"print(f'height is {h_m} meters')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"> Note: The `scipy.constants` \n",
"> [conversion factors](https://docs.scipy.org/doc/scipy/reference/constants.html#length) \n",
"> all convert to SI units.\n",
"\n",
"### Question 1\n",
"\n",
"The Capitol is 22 800 ft from Truax. How many meters is that?\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Example 2\n",
"\n",
"The SI unit of atmospheric pressure is the Pascal (Pa). \n",
"One Pascal is one Newton of force per square meter of area:\n",
"\n",
"$$1\\;\\rm{Pa} = 1 \\frac{\\rm{N}}{\\rm{m}^2}$$\n",
"\n",
"Standard Atmospheric Pressure is $1.013 \\times 10^5\\;\\rm{Pa}$. \n",
"Express this in pounds per square inch.\n",
"\n",
"> Notes: \n",
"> \n",
"> - to convert *from* (not *to*) SI units, you have to *divide* by the conversion factor.\n",
"> - to square a quantity, python uses a double-asterisk, as in `x**2`\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"p = 101300 # p is atmospheric pressure in N per m\u00b2\n",
"p = p / scipy.constants.lbf # p is now in lb per m\u00b2\n",
"p = p * scipy.constants.foot**2 # lb per ft\u00b2\n",
"p = p / 12**2 # lb per in\u00b2\n",
"print(f'Standard Atmospheric Pressure is {p} lb/in\u00b2')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Question 2\n",
"\n",
"A tire needs to be inflated to a pressure of $2.07 \\times 10^5$ Pa. \n",
"What is this pressure in lb/in\u00b2?\n",
"\n",
"> Hint: enter numbers in scientific notation with an `e`: $2.07 \\times 10^5$ = `2.07e5`.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Example 3\n",
"\n",
"You measure the diameter of a sphere to be $4.02 \\pm 0.02$ cm.\n",
"\n",
"Find the sphere's volume in cm$^3$ along with its absolute uncertainty.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"d = 4.02 # diameter, cm\n",
"unc_d = 0.02/d # relative uncertainty in d\n",
"r = 0.5*d # find radius\n",
"unc_r = unc_d\n",
"V = 4/3*pi * r**3 # use ** to raise to a power\n",
"unc_V = 3*unc_r\n",
"unc_V = unc_V * V # convert to absolute uncertainty \n",
"print(f'volume is {V} \u00b1 {unc_V} cm^3')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You can control the number of digits after the decimal that print out\n",
"with *string formatting* as follows:\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"print(f'volume is {V:.2f} \u00b1 {unc_V:.2f} cm^3')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"The `:.2f` directs python to show 2 decimal places of a \"floating point\" (ie,\n",
"decimal) value.\n",
"If you would like to use scientific notation, use an `e` instead of `f` as follows:\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"print(f'volume is {V:.2e} \u00b1 {unc_V:.2e} cm^3')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You can learn more about \n",
"[fancier printing](https://docs.python.org/3/tutorial/inputoutput.html)\n",
"in Python by [a web search](https://duckduckgo.com/?q=print+format+in+python&hps=1&atb=v339-7&ia=web).\n",
"\n",
"### Question 3\n",
"\n",
"Astronomers report the diameter of a planet to be $(6.37 \\pm 0.02) \\times 10^6$ m.\n",
"\n",
"Find the planet's volume in m$^3$ along with its absolute uncertainty.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Example 4\n",
"\n",
"The coordinates of point $P$ are measured to be \n",
"$x = 2.55 \\pm 0.02$ m, $y = 1.24 \\pm 0.04$ m. \n",
"What is the angle $\\theta$ (in degrees) and its uncertainty?\n",
"\n",
"Finding $\\theta$ requires the inverse tangent function \n",
"(also known as the *arctangent*) as follows.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"x = 2.55 # m\n",
"dx = 0.02 # m, absolute uncertainty\n",
"y = 1.24 # m\n",
"dy = 0.04 # m, absolute uncertainty\n",
"Q = arctan(y/x)\n",
"print(f'theta = {Q*180/pi} degrees')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Computers always work in radians, \n",
"so the last line converts the radians to degrees (`*180/pi`).\n",
"\n",
"We have no rule about propagating the uncertainty through an `arctan` function.\n",
"But we can find the range of values we would get when $x$ and $y$ are at the\n",
"edge of their uncertainty.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"print(f'the angle is theta = {Q*180/pi} degrees')\n",
"print(f'other theta values within our uncertainty are...')\n",
"print( arctan((y+dy)/(x+dx)) *180/pi )\n",
"print( arctan((y+dy)/(x-dx)) *180/pi )\n",
"print( arctan((y-dy)/(x+dx)) *180/pi )\n",
"print( arctan((y-dy)/(x-dx)) *180/pi )"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"So a good measure of the uncertainty in $\\theta$ is 1/2 of the difference \n",
"$\\max (\\theta) - \\min (\\theta)$. \n",
"Looking at the four values printed above, \n",
"you need to find the maximum and minimum.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"Q1 = arctan((y+dy)/(x-dx))*180/pi \n",
"Q2 = arctan((y-dy)/(x+dx))*180/pi\n",
"dQ = 0.5*( Q1 - Q2 )\n",
"print(f'theta = {Q*180/pi:.2f} \u00b1 {dQ:.2f} degrees')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"We've answered the question, but in case you're curious, \n",
"a better way to find the `min` and `max` would be to put the results in a \n",
"[Python list](https://docs.python.org/3/tutorial/introduction.html#lists) \n",
"(comma separated between square brackets) and then use the `min` and `max` functions:\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"Q_list = [ arctan((y+dy)/(x+dx)) *180/pi,\n",
" arctan((y+dy)/(x-dx)) *180/pi,\n",
" arctan((y-dy)/(x+dx)) *180/pi,\n",
" arctan((y-dy)/(x-dx)) *180/pi ]\n",
"dQ = 0.5*( max(Q_list) - min(Q_list) )\n",
"Q_ave = 0.5*( max(Q_list) + min(Q_list) )\n",
"print(f'theta = {Q*180/pi:.2f} \u00b1 {dQ:.2f} degrees')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Question 4\n",
"\n",
"A distance along a slope is measured to be $d=2.00 \\pm 0.02$ m. \n",
"The slope lies at an angle of $\\theta = 30.0 \\pm 0.1$ degrees above the horizontal. \n",
"The vertical height of this slope is given by \n",
"\n",
"$$y = d \\sin \\theta$$\n",
"\n",
"Find the value and uncertainty of $y$ (ie, find $y \\pm dy$).\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## C. (Optional) Importing packages\n",
"\n",
"If you have a computational problem to solve, \n",
"there's a good chance someone has already solved it. \n",
"Python's FLOSS \n",
"([free-libre open source software](https://en.wikipedia.org/wiki/Free_and_open-source_software))\n",
"philosophy lends itself to community-shared solutions.\n",
"\n",
"For example, you might wonder if anyone has written code to automatically\n",
"handle uncertainty calculations. Answering this kind of question is best done\n",
"with an internet search for, in this case, \n",
"\"[python uncertainty](https://duckduckgo.com/?q=python+uncertainty)\". \n",
"You would quickly learn that the `uncertainties` package is popular. \n",
"\n",
"However, you cannot import it since it does not come with the standard\n",
"Python/Jupyter installation. You will receive an `import error` if you execute\n",
"the `import` line below before installing the package. \n",
"In this case (and for many [Python packages](https://pypi.python.org/pypi)), \n",
"installation is easy. Execute the following at a command line:\n",
"\n",
" pip install uncertainties\n",
"\n",
"> Note: You can obtain a command line in Windows by running app `cmd`,\n",
"> in a Mac by launching a `terminal`.\n",
"> This is not available in `jupyter.org/try`.\n",
"\n",
"Now you may import and use the package. \n",
"Check its [documentation](http://pythonhosted.org/uncertainties/user_guide.html) \n",
"for how to use it.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"import uncertainties"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now uncertainty calculations can be done automatically (and more accurately)! \n",
"\n",
"Consider Example 3, above, using this package.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"d = uncertainties.ufloat(3.14, 0.02) # from Example 3, above\n",
"r = 0.5*d\n",
"V = 4/3*pi * r**3\n",
"print(f'volume is {V} cm^3')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## D. Vectors in Python\n",
"\n",
"\n",
"\n",
"Suppose we know the vector sum $\\vec{F_1} +\\vec{F_2} + \\vec{F_3} = \\vec{0}$,\n",
"and we are given the following information.\n",
"\n",
"- vector $\\vec{F_1}$ lies along the positve $x$ axis, with magnitude 200 N\n",
"- vector $\\vec{F_2}$ makes an angle of $107^{\\circ}$ with the $+x$ axis, \n",
" and has magnitude 300 N\n",
"\n",
"Answer the following questions:\n",
"\n",
"1. What is the direction and magnitude of vector $\\vec{F_{4}} = \\vec{F_1} + \\vec{F_2}$ ?\n",
"2. What must be the direction and magnitude of vector $\\vec{F_3}$ ?\n",
"\n",
"----------------------------------\n",
"\n",
"**Solution**\n",
"\n",
"First we need to define vectors $\\vec{F_1}$ and $\\vec{F_2}$. \n",
"In Python, this is done with the `array` statement.\n",
"Here are two equivalent ways we could define $\\vec{F_1}$ :\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"F1 = array(( 200, 0 )) # specify the components of F1\n",
"F1 = 200 * array(( 1, 0 )) # write F1 as a scalar times a unit vector"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"For $\\vec{F_2}$ it's easier to use the unit vector form. \n",
"All angles must be in radians.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"Q = 107*pi/180 # angle in radians \n",
"F2 = 300 * array(( cos(Q), sin(Q) ))"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"If you add the variables `F1` and `F2`, \n",
"it will (correctly) add the components of the vectors.\n",
"Let's add them and call the sum $\\vec{F_{4}}$:\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"F4 = F1 + F2\n",
"print('F4 = ',F4)"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"This means that $\\vec{F_{4}} = 112 \\hat{\\imath} + 287 \\hat{\\jmath}$ N.\n",
"\n",
"Let's find the magnitude of this vector: $F = \\sqrt{ F_x^2 + F_y^2}$.\n",
"\n",
"- to square a Python array use `F4**2`; this will square each component individually\n",
"- `sum` will add up all the (squared) array components\n",
"- `sqrt` is the square root\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"mag = sqrt(sum(F4**2))\n",
"print(f\"magnitude of F4 is {mag} N\")"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"To find the direction of $\\vec{F}$, we use \n",
"$\\theta = \\arctan \\left (\\frac{F_y}{F_x} \\right )$. \n",
"\n",
"The components of a python array are accessed by indexing them, \n",
"starting from zero, like this: \n",
"\n",
"$F_x =$ `F4[0]`\n",
"\n",
"$F_y =$ `F4[1]`\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"angle = arctan( F4[1] / F4[0] )\n",
"print(f'angle is {angle*180/pi} degrees') # convert rad to degrees"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"The vector $\\vec{F_3}$ should be in the opposite direction to $\\vec{F_{4}}$.\n",
"So it should have the same magnitude with an angle \n",
"$\\theta+180^{\\circ}$ or $\\theta+\\pi$ radians.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"F3 = mag * array(( cos(angle+pi), sin(angle+pi) ))\n",
"print(\"F3 =\",F3)"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"We know that \n",
"$\\vec{F}_3 = -\\left (\\vec{F_1} +\\vec{F_2} \\right ) = -\\vec{F_{4}}$. \n",
"Look above and note that the components of $\\vec{F_3}$ are the\n",
"negative of the components of $\\vec{F_{4}}$.\n",
"\n",
"That's it, we're done. \n",
"The following code block summarizes the operations required to answer the question.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"F1 = 200 * array(( 1, 0 ))\n",
"F2 = 300 * array(( cos(107*pi/180), sin(107*pi/180) ))\n",
"F4 = F1 + F2\n",
"mag = sqrt(sum(F4**2))\n",
"angle = arctan(F4[1]/F4[0])\n",
"print(f'magnitude of F4 is {mag:0.2f} N and its direction is {angle*180/pi:0.2f} degrees')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### A Note about `arctan`\n",
"\n",
"The `arctan` function above has a problem: \n",
"it can give only give angles between $-\\pi/2$ and $+\\pi/2$, \n",
"in the first and fourth quadrants. \n",
"This is because the computer cannot distinguish between, for example, \n",
"`arctan(-1/1)`, which should be $- \\pi/4$ and \n",
"`arctan(1/-1)`, which should be $3 \\pi/4$.\n",
"\n",
"The solution is to use the `arctan2(y,x)` function, \n",
"giving it the $y$ and $x$ values individually \n",
"(not their ratio) so it knows which angle to return.\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [
"print('arctan(1/-1)=',arctan(1/-1)*180/pi)\n",
"print(' wrong quatrant!')\n",
"print('arctan2(1,-1)=',arctan2(1,-1)*180/pi)\n",
"print(' correct!')"
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"> Note the `arctan2` function requires `y,x`, not `y/x`.\n",
"\n",
"## E. Vector Problems\n",
"\n",
"Now it's your turn.\n",
"\n",
"Find the magnitude and direction of the following vectors. Give your answers as follows:\n",
"\n",
"- all values are decimals expressed with three significant figures\n",
"- directions are angles in degrees off the $+x$ axis \n",
" (postive angles for counterclockwise and negative angles for clockwise)\n",
"\n",
"(a) $\\vec{A} = - \\frac{1}{\\sqrt{2}} \\hat{\\imath} - \\frac{1}{\\sqrt{2}} \\hat{\\jmath}$\n",
"\n",
"(b) $\\vec{B} = - 10 \\hat{\\imath} + 10 \\hat{\\jmath}$\n",
"\n",
"(c) $\\vec{C} = 1000 \\hat{\\imath} - \\hat{\\jmath}$\n",
"\n",
"(d) $10\\vec{A} - \\frac{\\vec{B}}{2}$\n"
],
"metadata": {}
},
{
"cell_type": "code",
"source": [],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"> Hint: for question (d), you can write `10*A - B/2` \n",
"> (assuming you defined `A` and `B` correctly).\n"
],
"metadata": {}
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}