Homework 9¶
Problem 1¶
Carefully read all of the notes on functions. Pay special attention to the code cells.
Just state if you did this.
Problem 2¶
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)
- The
np.part is because we imported the libraryas np. - If we had just done
import numpythen we would usenumpy.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
Problem 3¶
Write a function to compute the volume of a sphere given it's radius. Get $\pi$ from numpy.
Problem 4¶
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$.
Problem 5¶
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$.
Problem 6¶
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
- $f(x) = x^2$ for $x=3$.
- $f(x) = \sin(x)$ for $x=\pi/2$
- $f(x) = \exp(x)$ for $x=1.01325$
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.
Problem 7¶
Have AI solve Problem 6 and copy the resulting code here? Which AI tool did you use? What is different? Do you have any questions about its results? Do you understand its code?