Code
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
# --- 1. Define Symbols and the ODE ---
= sp.Symbol('t', positive=True)
t = sp.Symbol('s')
s = sp.Function('y')
y
# Define the differential equation: y'(t) + y(t) - 1 = 0
= y(t).diff(t) + y(t) - 1
ode
# --- 2. Solve directly using SymPy's dsolve with Laplace method ---
# This automates the transform, solve, and inverse transform steps.
# We provide the initial condition y(0)=0 via the 'ics' argument.
= sp.dsolve(ode, ics={y(0): 0})
solution
# Display the symbolic solution
print("The symbolic solution is:")
display(solution)= solution.rhs # Extract the right-hand side for plotting
y_t
# --- 3. Visualize the Solution ---
# Convert the symbolic solution into a numerical function for plotting
= sp.lambdify(t, y_t, modules=['numpy'])
y_func
# Generate time values for the plot
= np.linspace(0, 5, 400)
t_vals = y_func(t_vals)
y_vals
# Plot the result
=(8, 5))
plt.figure(figsize=f"y(t) = {y_t}", color='blue')
plt.plot(t_vals, y_vals, label"Solution of y' + y = 1 using Laplace Transform")
plt.title("Time (t)")
plt.xlabel("y(t)")
plt.ylabel(True)
plt.grid(
plt.legend() plt.show()
The symbolic solution is:
\(\displaystyle y{\left(t \right)} = 1 - e^{- t}\)
