# Define a return to scale
scale = 1 # Constant return to scale, i.e. Homogeneous function of degree 1
# Define parameter a
a = 1/4
# total wealth of x
k_x = 2
# total wealth of y
k_y = 2
import numpy as np
import matplotlib.pyplot as plt
# 경고 메시지 숨기기
np.seterr(invalid='ignore')
def numerical_derivative(f, X, Y, h=1e-5):
""" Compute numerical partial derivatives using central difference method."""
dfdx = (f(X + h, Y) - f(X - h, Y)) / (2 * h) # ∂f/∂x
dfdy = (f(X, Y + h) - f(X, Y - h)) / (2 * h) # ∂f/∂y
return dfdx, dfdy
# Define functions u_1(x,y) = x^a * y^(1-a) and u_2(x,y) = (2-x)(2-y)
def u1(x, y):
return x**(scale*a) * y**(scale*(1-a))
def u2(x, y):
return (k_x - x)**(scale*a) * (k_y - y)**(scale*(1-a))
# Define the grid
x = np.linspace(0, k_x, 15)
y = np.linspace(0, k_y, 15)
X, Y = np.meshgrid(x, y)
# Compute the numerical derivatives (vector field components)
U1, V1 = numerical_derivative(u1, X, Y)
U2, V2 = numerical_derivative(u2, X, Y)
# Reduce the density of vectors for better visualization
x_sparse = np.linspace(0, k_x, 8)
y_sparse = np.linspace(0, k_y, 8)
X_sparse, Y_sparse = np.meshgrid(x_sparse, y_sparse)
U1_sparse, V1_sparse = numerical_derivative(u1, X_sparse, Y_sparse)
U2_sparse, V2_sparse = numerical_derivative(u2, X_sparse, Y_sparse)
# Plot the combined vector fields and contour plots
#plt.figure(figsize=(8, 8))
# Contour plots of u_1 and u_2 (level curves only)
contour1 = plt.contour(X, Y, u1(X, Y), colors='blue', linestyles='solid', linewidths=1)
contour2 = plt.contour(X, Y, u2(X, Y), colors='red', linestyles='dashed', linewidths=1)
# Overlay vector fields
plt.quiver(X_sparse, Y_sparse, U1_sparse, V1_sparse, color='b', angles='xy', label='∇$u_1$')
plt.quiver(X_sparse, Y_sparse, U2_sparse, V2_sparse, color='r', angles='xy', label='∇$u_2$')
# Labels and grid
plt.xlabel('x')
plt.ylabel('y')
plt.title('Gradient Vector Fields & Level Curves of $u_1$ and $u_2$')
plt.legend()
plt.grid('scaled')
plt.axis('square')
plt.tight_layout()
# Show the plot
plt.show()
# Compute the sum of gradients
U_sum = U1 + U2
V_sum = V1 + V2
# Reduce the density of vectors for better visualization
U_sum_sparse, V_sum_sparse = numerical_derivative(lambda x, y: u1(x, y) + u2(x, y), X_sparse, Y_sparse)
# Plot the combined vector fields and contour plots
#plt.figure(figsize=(8, 8))
# Contour plots of u_1 and u_2 (level curves only)
contour1 = plt.contour(X, Y, u1(X, Y), colors='blue', linestyles='solid', linewidths=1)
contour2 = plt.contour(X, Y, u2(X, Y), colors='red', linestyles='dashed', linewidths=1)
# Overlay sum of gradient vector fields
plt.quiver(X_sparse, Y_sparse, U_sum_sparse, V_sum_sparse, color='g', angles='xy', label='∇($u_1 + u_2$)')
# Labels and grid
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sum of Gradient Vector Fields & Level Curves of $u_1$ and $u_2$')
plt.legend()
plt.grid('scaled')
plt.axis('square')
# Show the plot
plt.show()