Cycle 04
Lab Cycle 4 — Scientific Computing & Data Visualization (NumPy & Matplotlib)
Display Sine, Cosine, Polynomial, and Exponential Curves
Problem Statement
Write a Python program that makes use of a function to display sine, cosine, polynomial, and exponential curves using Matplotlib and NumPy.
import numpy as np
import matplotlib.pyplot as plt
def plot_mathematical_curves():
"""
Computes and displays 4 mathematical curves in a 2x2 subplot layout:
1. Sine Curve: y = sin(x)
2. Cosine Curve: y = cos(x)
3. Polynomial Curve: y = x^3 - 4x
4. Exponential Curve: y = e^x
"""
# Generate domain points
x_trig = np.linspace(-2 * np.pi, 2 * np.pi, 300)
x_poly = np.linspace(-3, 3, 300)
x_exp = np.linspace(-2, 3, 300)
fig, axes = plt.subplots(2, 2, figsize=(12, 9))
fig.suptitle("Mathematical Functions Visualization", fontsize=16, fontweight='bold')
# 1. Sine Curve
axes[0, 0].plot(x_trig, np.sin(x_trig), color='blue', linewidth=2, label=r'$y = \sin(x)$')
axes[0, 0].set_title("Sine Curve", fontsize=12, fontweight='bold')
axes[0, 0].set_xlabel("x (radians)")
axes[0, 0].set_ylabel("sin(x)")
axes[0, 0].grid(True, linestyle='--', alpha=0.7)
axes[0, 0].legend()
# 2. Cosine Curve
axes[0, 1].plot(x_trig, np.cos(x_trig), color='green', linewidth=2, label=r'$y = \cos(x)$')
axes[0, 1].set_title("Cosine Curve", fontsize=12, fontweight='bold')
axes[0, 1].set_xlabel("x (radians)")
axes[0, 1].set_ylabel("cos(x)")
axes[0, 1].grid(True, linestyle='--', alpha=0.7)
axes[0, 1].legend()
# 3. Polynomial Curve (y = x^3 - 4x)
y_poly = x_poly**3 - 4 * x_poly
axes[1, 0].plot(x_poly, y_poly, color='crimson', linewidth=2, label=r'$y = x^3 - 4x$')
axes[1, 0].set_title("Polynomial Curve ($y = x^3 - 4x$)", fontsize=12, fontweight='bold')
axes[1, 0].set_xlabel("x")
axes[1, 0].set_ylabel("y")
axes[1, 0].grid(True, linestyle='--', alpha=0.7)
axes[1, 0].legend()
# 4. Exponential Curve (y = e^x)
axes[1, 1].plot(x_exp, np.exp(x_exp), color='purple', linewidth=2, label=r'$y = e^x$')
axes[1, 1].set_title("Exponential Curve ($y = e^x$)", fontsize=12, fontweight='bold')
axes[1, 1].set_xlabel("x")
axes[1, 1].set_ylabel("e^x")
axes[1, 1].grid(True, linestyle='--', alpha=0.7)
axes[1, 1].legend()
plt.tight_layout()
plt.show()
if __name__ == "__main__":
plot_mathematical_curves()
Question 2 of 3