from sympy import *
= symbols('x', real = True)
x 4*x-5, x) solve(
[5/4]
Just like our first three sessions, the idea of these labs is for you to learn enough so that you can use SymPy to help you out when checking answers if you work on examples and exercises in our book.
Our goals for today are:
from sympy import *
= symbols('x', real = True)
x 4*x-5, x) solve(
[5/4]
4*x-5, x, dict = True) solve(
[{x: 5/4}]
It may sometimes be convenient to have dict = True
because this dictionary form of the output is useful for quick substitutions.
from sympy import *
= symbols('x y', real = True)
x, y -4*x-2*y+36, -2*x-4*y+42], [x, y]) solve([
{x: 5, y: 8}
-4*x-2*y+36, -2*x-4*y+42], [x, y], dict = True) solve([
[{x: 5, y: 8}]
Combine what you have learned here and what you have learned in the past about derivatives. Do Section 13.1 Example 1 completely. Start from encoding the function to be maximized in SymPy, get first derivatives, and look for stationary points.
It may be useful, especially for Chapter 13, to draw surfaces, traces, and contours in Python. We are going to use matplotlib
and numpy
, because plotting in SymPy is slightly limited and SymPy also somewhat relies on matplotlib
. All codes used for this section are based on
matplotlib
website which has an extensive gallery and quite a long list of tutorialsimport matplotlib.pyplot as plt
import numpy as np
= np.linspace(0, 10, 200)
x = np.sin(x)
y = plt.subplots()
fig, ax
ax.plot(x, y) plt.show()
matplotlib
is so extensive that you can easily be overwhelmed. Always think about what you want to show first before trying out the many different options.
= plt.subplots()
fig, ax 'r-', linewidth=2, label='$y=\sin(x)$', alpha=0.6)
ax.plot(x, y, ='upper center')
ax.legend(loc-1, 0, 1])
ax.set_yticks([0, 5, 10])
ax.set_xticks(['Test plot')
ax.set_title( plt.show()
For 3D surfaces, let use revisit Section 13.1 Example 1. Here you will get a sense of the contours of the surface in that example.
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
return -2*x**2-2*x*y-2*y**2+36*x+42*y-158
= np.linspace(0, 15, 100)
x = np.linspace(0, 15, 100)
y # Pay attention to the case of the letters!!!!
= np.meshgrid(x, y)
X, Y = f(X, Y)
Z
= plt.figure()
fig = plt.axes(projection='3d')
ax 100)
ax.contour3D(X, Y, Z, 'x')
ax.set_xlabel('y')
ax.set_ylabel('z'); ax.set_zlabel(
If you want the traces of the surface where you essentially take “slices” of the surface, you can use the code below. For example, what would
0)) plt.plot(x, f(x,
Next, what would
0, y)) plt.plot(y, f(
Finally, it may be useful to see what happens to these slices when we fix y at 8 and then x at 5. Why do you think I am doing this?
8)) plt.plot(x, f(x,
5, y)) plt.plot(y, f(
It is possible to make all of these fancier, but I think it depends on what visualizations you want. Think about that first before laying out a canvas.
Do Section 13.2 Example 1 completely.