Carefully read all of the notes on functions. Pay special attention to the code cells.
Just state if you did this.
There are lots of libraries available for importing functions in python. One of the most important is numpy.
Type the following in a code cell
import numpy as np
This imports the numpy library. To take $\sqrt x$ we use np.sqrt(x)
import numpy
then we would use numpy.sqrt(x)
, but that is less concise.Browse the functions at this site and try a couple of them out.
Here is another good numpy reference
Write a function to compute the volume of a sphere given it's radius. Get $\pi$ from numpy.
Write a function to compute the vapor pressure of a species given $A$, $B$, and $C$ according to the following equation
$$P_i^{sat} = \exp\left(A + \frac{B}{T+C}\right).$$Assume $T$ has units of K. Include a docstring documenting the function. Use numpy for $\exp$.
A function can return more than two quantities, say x1
and x2
if you use the following return statement
return x1, x2
, where x1
and x2
are variables or expressions.
You would the call the function as
x1,x2 = f(a,b,c)
.
Write a function that will return the two roots of a quadratic equation $ax^2+bx+c=0$, given $a$, $b$, and $c$. Assume the roots are real.
Try out the function for $x^2-5x+5$.
The first derivative of a function $f(x)$ can be approximated as $$\frac{df(x)}{dx} \approx \frac{f(x+\Delta x) - f(x)}{\Delta x}.$$ A good estimate for $\Delta x$ is $$\Delta x = \epsilon|x|,$$ where $\epsilon$ is a small number.
Write a function called derivative
that takes f
, x
, and eps
as arguments and returns the derivative evaluated at x
. Here, f
is a function, x
is where you are evaluating the derivative, and eps
is $\epsilon$ in the above equation. Give eps
a default value of $10^{-8}$.
Test it out on the following
In each case, compare to the exact solution.
For $\sin$ and $\exp$, you can use numpy and call the derivative function like so
d = derivative(np.sin, np.pi/2)
d = derivative(np.exp, 1.01325)
For $f(x)=x^2$, you will need to write your own function that you can pass to the derivative
function.