trapezoid ANIMATION production

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter

# Define the new function to integrate: x * log(x)
def func(x):
    # Avoid log(0) by returning 0 when x is 0
    return np.where(x == 0, 0, x * np.log(x))

# Set up the figure and axis
fig, ax = plt.subplots()
a, b = 0.01, 2  # Define the interval [a, b] avoiding 0 to prevent log(0) issues
x_vals = np.linspace(a, b, 1000)
ax.plot(x_vals, func(x_vals), 'r', label=r'$x \log(x)$')
ax.set_ylim(-1, 2)
ax.set_xlim(a, b)

# Title and labels
ax.set_title('Numerical Integration Process using Trapezoidal Rule for $x \log(x)$')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()

# Fill area under the curve (for animation purposes)
patches = []  # To store the artists

# Define the number of trapezoids to draw
n_trapezoids = 50
x_points = np.linspace(a, b, n_trapezoids + 1)
y_points = func(x_points)

# Function to update the animation at each step
def update(frame):
    global patches
    for patch in patches:
        patch.remove()
    patches = []
    
    # Plot the new trapezoid for the current frame
    if frame > 0:
        patch = ax.fill_between([x_points[frame-1], x_points[frame]], [y_points[frame-1], y_points[frame]], 
                                color='lightblue', alpha=0.5)
        patches.append(patch)  # Store the artist
    
    # Redraw the whole plot with current trapezoids filled
    for i in range(1, frame):
        patch = ax.fill_between([x_points[i-1], x_points[i]], [y_points[i-1], y_points[i]], color='lightblue', alpha=0.5)
        patches.append(patch)  # Store each trapezoid artist

# Create the animation
ani = FuncAnimation(fig, update, frames=range(1, n_trapezoids+1), interval=200, repeat=False)

# Save the animation as an MP4 file using FFmpeg
mp4_writer = FFMpegWriter(fps=10, metadata=dict(artist='Me'), bitrate=1800)
ani.save("integration_animation_xlogx.mp4", writer=mp4_writer)

# Optionally, show the animation (if you still want to display it)
plt.show()

Leave a Reply

Your email address will not be published. Required fields are marked *