Untitled

 avatar
unknown
plain_text
17 days ago
1.8 kB
2
Indexable
import numpy as np
import matplotlib.pyplot as plt

def plot_inverse(f, f_inv, x_range, label_f, label_f_inv, restriction=None):
    x = np.linspace(*x_range, 400)
    y = f(x)

    plt.plot(x, y, label=label_f, color='dodgerblue')

    if restriction:
        x_inv = np.linspace(*restriction, 400)
    else:
        x_inv = np.linspace(*x_range, 400)

    plt.plot(f_inv(x_inv), x_inv, label=label_f_inv, color='hotpink')

    plt.plot(x, x, '--', color='gray')  # y = x line

plt.figure(figsize=(12, 8))

# a) f(x) = x^2 + 3
plt.subplot(2, 3, 1)
plot_inverse(lambda x: x**2 + 3, lambda x: np.sqrt(x - 3), (-3, 3), r'$f(x) = x^2 + 3$', r'$f^{-1}(x) = \sqrt{x - 3}$', (3, 12))
plt.title('a)')

# b) f(x) = (1/2) * x^2
plt.subplot(2, 3, 2)
plot_inverse(lambda x: 0.5 * x**2, lambda x: np.sqrt(2 * x), (-3, 3), r'$f(x) = \dfrac{1}{2}x^2$', r'$f^{-1}(x) = \sqrt{2x}$', (0, 12))
plt.title('b)')

# c) f(x) = -2x^2
plt.subplot(2, 3, 3)
plot_inverse(lambda x: -2 * x**2, lambda x: -np.sqrt(-x / 2), (-3, 3), r'$f(x) = -2x^2$', r'$f^{-1}(x) = -\sqrt{-\dfrac{x}{2}}$', (0, 0))
plt.title('c)')

# d) f(x) = (x + 1)^2
plt.subplot(2, 3, 4)
plot_inverse(lambda x: (x + 1)**2, lambda x: -1 + np.sqrt(x), (-3, 3), r'$f(x) = (x + 1)^2$', r'$f^{-1}(x) = -1 + \sqrt{x}$', (0, 12))
plt.title('d)')

# e) f(x) = -(x - 3)^2
plt.subplot(2, 3, 5)
plot_inverse(lambda x: -(x - 3)**2, lambda x: 3 - np.sqrt(-x), (0, 6), r'$f(x) = -(x - 3)^2$', r'$f^{-1}(x) = 3 - \sqrt{-x}$', (-12, 0))
plt.title('e)')

# f) f(x) = (x - 1)^2 - 2
plt.subplot(2, 3, 6)
plot_inverse(lambda x: (x - 1)**2 - 2, lambda x: 1 + np.sqrt(x + 2), (-3, 5), r'$f(x) = (x - 1)^2 - 2$', r'$f^{-1}(x) = 1 + \sqrt{x + 2}$', (-2, 12))
plt.title('f)')

plt.tight_layout()
plt.show()
Editor is loading...
Leave a Comment