Sample Code
Consider the following Python code, which comes from Section 0.2.5 of the MTH 306 Textbook. The code verifies that $x(t) = Ce^{-t} + \sin(t) + \cos(t)$ satisfies the differential equation $\frac{dx}{dt} + x = 2\cos(t)$, then plots some solutions for different choices of $C$.
The code first construct the family of solutions, $x(t) = Ce^{-t} + \sin(t) + \cos(t)$.
* sp.exp is the exponential function (i.e. sp.exp(x) means $e^x$)
* sp.sin is the sine function
* sp.cos is the cosine function
[13]: t, C = sp.symbols('t C')
x = C*sp.exp(-t) + sp.sin(t) + sp.cos(t)
[14]: x
[14]: $Ce^{-t} + \sin(t) + \cos(t)$
The code then verifies that the above family of solutions satisfy the differential equation $\frac{dx}{dt} + x = 2\cos t$.
* sp.diff(x,t) computes the derivative $\frac{dx}{dt}$
* the double equal symbol == is a check for equality. It returns True is both sides are equal and False if not.
[14]: sp.diff(x,t) + x == 2*sp.cos(t)
[14]: True
Checking (...left-hand side...) == (...right-hand side...) tests whether the two expressions are identical. It will not catch if they are different but equivalent, like $\cos^2 t$ and $1 - \sin^2 t$. A more robust tactic is to test if (...left-hand side...) - (...right-hand side...) simplifies to 0:
* sp.simplify will try to simplify an algebraic expression
[17]: sp.simplify( sp.diff(x,t) + x - 2*sp.cos(t)) == 0
[17]: True
The code then generates a few different solutions for different choices of $C$. In particular, we build a list of three solutions, where $C = -2, C = 0$, and $C = 1$.
[20]: afewsolutions = [x.subs({C:c}) for c in [-2,0,1]]
afewsolutions
[20]: $[\sin(t) + \cos(t) - 2e^{-t}, \sin(t) + \cos(t), \sin(t) + \cos(t) + e^{-t}]$
The code then loops through each of these particular solutions and plots them for $0 \le t \le 5$.
[23]: for solution in afewsolutions:
expressionplot( solution, t, 0, 5 )
plt.grid()
plt.show()
Exercise 1.
Modify the sample code above to verify that $x(t) = \frac{1}{2} + Ce^{-t}$ is a family of solutions to the $1^{st}$-order differential equation $\frac{dx}{dt} + 2x = t$. Plot the particular solutions for the 3 IVPs: $x(0) = \frac{3}{2}$; $x(0) = -\frac{5}{2}$; $x(0) = -\frac{1}{2}$ (you will need to determine the correct values of $C$ that give these initial conditions). If necessary, adjust the parameters so that the graphs are clearly displayed.
Put your modified code in cells below.
In Python, we use a double-asterisk (**) to denote powers, not a caret (^). That is, t**n represents $t^n$.
[26]: # Define a family of functions, x(t)
[28]: # Verify that the family of functions satisfies the differential equation
[1]: # Build a list of solutions satisfying the given initial conditions
[2]: # Plot the solutions satisfying the given initial conditions