import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def plot_differential_equations():
equations = [eq_a, eq_b, eq_c, eq_d]
titles = ['y dy/dx = -x; y(1) = 4',
'dy/dx = 1/y; y(0) = 1',
'dy/dx = 0.2x^2 + y; y(0) = 1/2',
'y\' = y - cos(π/2 * x); y(2) = 2']
initial_conditions = [[1, 4], [0, 1], [0, 1/2], [2, 2]]
fig, axs = plt.subplots(2, 2, figsize=(15, 15))
axs = axs.flatten()
for i, (eq_func, title_str, initial_condition) in enumerate(zip(equations, titles, initial_conditions)):
plot_equation(eq_func, title_str, initial_condition, axs[i])
plt.tight_layout()
plt.show()
def plot_equation(eq_func, title_str, initial_condition, ax):
x, y = np.meshgrid(np.linspace(-5, 5, 20), np.linspace(-5, 5, 20))
dx, dy = eq_func(x, y)
# Normalizar las pendientes para una mejor visualización
L = np.sqrt(dx**2 + dy**2)
dx = dx / L
dy = dy / L
# Graficar el campo de direcciones
ax.quiver(x, y, dx, dy, color='r', alpha=0.5)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title(title_str)
ax.grid(True)
# Definir los valores iniciales y resolver la ecuación diferencial en ambas direcciones
x0, y0 = initial_condition
x_span1 = np.linspace(x0, 5, 100) # Rango positivo de x
x_span2 = np.linspace(x0, -5, 100) # Rango negativo de x
# Usar odeint para resolver la ecuación diferencial en el rango positivo
y_sol1 = odeint(lambda y, x: eq_func(x, y)[1], y0, x_span1)
# Usar odeint para resolver la ecuación diferencial en el rango negativo
y_sol2 = odeint(lambda y, x: eq_func(x, y)[1], y0, x_span2)
# Graficar la solución particular en el campo de direcciones
ax.plot(x_span1, y_sol1, 'b', linewidth=2)
ax.plot(x_span2, y_sol2, 'b', linewidth=2)
# Mostrar leyenda
ax.legend(['Campo de Direcciones', 'Solución Particular'], loc='best')
# Definiciones de las ecuaciones diferenciales
def eq_a(x, y):
return np.ones_like(x), -x / y
def eq_b(x, y):
return np.ones_like(x), 1 / y
def eq_c(x, y):
return np.ones_like(x), 0.2 * x**2 + y
def eq_d(x, y):
return np.ones_like(x), y - np.cos(np.pi/2 * x)
# Llamar a la función principal
plot_differential_equations()script.py:44: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information. y_sol1 = odeint(lambda y, x: eq_func(x, y)[1], y0, x_span1) script.py:47: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information. y_sol2 = odeint(lambda y, x: eq_func(x, y)[1], y0, x_span2)
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def f(y, x):
return -x / y
def plot_direction_field(ax, f, x_range, y_range, nx=20, ny=20):
x = np.linspace(x_range[0], x_range[1], nx)
y = np.linspace(y_range[0], y_range[1], ny)
X, Y = np.meshgrid(x, y)
dx = np.ones_like(X)
dy = f(Y, X)
length = np.sqrt(dx**2 + dy**2)
dx /= length
dy /= length
ax.quiver(X, Y, dx, dy, color='b', alpha=0.3)
# Configuración de la figura
fig, ax = plt.subplots(figsize=(10, 8))
# Campo direccional
plot_direction_field(ax, f, [-5, 5], [-5, 5])
# Valor inicial
x0, y0 = 1, 4
# Solución particular (hacia adelante)
x_forward = np.linspace(x0, 5, 1000)
y_forward = odeint(f, y0, x_forward)
# Solución particular (hacia atrás)
x_backward = np.linspace(x0, -3, 1000)
y_backward = odeint(f, y0, x_backward)
# Graficar soluciones
ax.plot(x_forward, y_forward, 'r-', linewidth=2)
ax.plot(x_backward, y_backward, 'r-', linewidth=2)
# Marcar el punto inicial
ax.plot(x0, y0, 'go', markersize=10)
ax.annotate(f'({x0}, {y0})', (x0, y0), xytext=(5, 5), textcoords='offset points')
ax.set_title('A) y dy/dx = -x; y(1) = 4')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.axhline(y=0, color='k', linestyle='--')
ax.axvline(x=0, color='k', linestyle='--')
ax.legend(['Campo direccional', 'Solución particular', 'Punto inicial'])
plt.show()script.py:33: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information. y_forward = odeint(f, y0, x_forward)
function ecuacionDiferencialA()
% A) y dy/dx = -x; y(1) = 4
figure;
hold on;
% Campo direccional
[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);
dX = ones(size(X));
dY = -X ./ Y;
quiver(X, Y, dX, dY, 'b');
% Valor inicial
x0 = 1;
y0 = 4;
% Solución particular (hacia adelante)
[x_forward, y_forward] = ode45(@odefun, [x0 5], y0);
plot(x_forward, y_forward, 'r', 'LineWidth', 2);
% Solución particular (hacia atrás)
[x_backward, y_backward] = ode45(@odefun, [x0 -3], y0);
plot(x_backward, y_backward, 'r', 'LineWidth', 2);
% Marcar el punto inicial
plot(x0, y0, 'go', 'MarkerSize', 10, 'MarkerFaceColor', 'g');
text(x0, y0, ' (1, 4)', 'VerticalAlignment', 'bottom');
title('A) y dy/dx = -x; y(1) = 4');
xlabel('x');
ylabel('y');
grid on;
axis equal;
legend('Campo direccional', 'Solución particular', 'Punto inicial', 'Location', 'best');
hold off;
end
function dydt = odefun(x, y)
dydt = -x ./ y;
endimport numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def odefun(y, x):
return -x / y
def ecuacion_diferencial_a():
# Define the grid for the direction field
X, Y = np.meshgrid(np.arange(-5, 5.5, 0.5), np.arange(-5, 5.5, 0.5))
dX = np.ones_like(X)
dY = -X / Y
# Create the direction field
plt.figure()
plt.quiver(X, Y, dX, dY, color='b')
# Initial conditions
x0 = 1
y0 = 4
# Solve the ODE forward
x_forward = np.linspace(x0, 5, 100)
y_forward = odeint(odefun, y0, x_forward)
# Solve the ODE backward
x_backward = np.linspace(x0, -3, 100)
y_backward = odeint(odefun, y0, x_backward)
# Plot the solutions
plt.plot(x_forward, y_forward, 'r', linewidth=2, label='Solución hacia adelante')
plt.plot(x_backward, y_backward, 'r', linewidth=2, label='Solución hacia atrás')
# Mark the initial point
plt.plot(x0, y0, 'go', markersize=10, markerfacecolor='g')
plt.text(x0, y0, ' (1, 4)', verticalalignment='bottom')
# Set title and labels
plt.title('A) y dy/dx = -x; y(1) = 4')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.axis('equal')
plt.legend(loc='best')
plt.show()
# Run the function
ecuacion_diferencial_a()
# This code replicates the functionality of the provided MATLAB code by computin
# g and visualizing the direction field of the differential equation \(y \frac{d
# y}{dxscript.py:29: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information. y_forward = odeint(odefun, y0, x_forward)