cover

I Got Bored, And “Made” A Pendulum in Python

    Published 2024-11-23

        Python

        programming

        productivity

        personal

        for fun

    First off, let me get this out of the way: I did this tiny project with a friend and a half.

    During my job yesterday, me and a fellow friend actually went and played with MatPlotLib, ChatGPT to build a pendulum using Python.

    Honestly, I got excited since I always like to find excuses to use other languages. I definitely like JavaScript, do not get me wrong (like all developers) but I find it hard to pick up huge creative projects for other languages. I want to do something more machine learning-based, which will most likely use Python since it is the gold standard currently. Then there is more root programming. stuff more for Arduinos and Lower-Level (C++).

    When I go to college, I want to learn how to do some game engine development, just as an excuse to really get in the pins and needles of C++.

    For now though, I decided to with the help of ChatGPT, write a pendulum swinging graph.

    I did run into a few fun kinks in mine, however.

    For some reason, the libraries used to render the graph did not work well with PyCharm. Maybe it is the professional edition being the reason, but I had to find a workaround.

    Hence, I figured out I could turn it into a video. The top result was output straight from the code after the pendulum had finished running.

    I also managed to understand a new physics equation, which is great since I will be continuing my physics journey for the next few semesters!

    Anyways, I have a GitHub repo right here with the working code, but here is just the code itself. I will touch on the specifics and then the full code with be on the bottom :d

    first, we setup the variables:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    g = 9.8  # gravity, 9.8 is earth's.
    L = 1.0  # length of pendulum, this will affect speed
    theta = np.pi / 4  # starting angle (in radians)
    omega = 0  # initial angular velocity
    dt = 0.01  # time step (in seconds)

    we also need to get our variables to store for later.

    angles = []
    times = []

    Then, here is our function to plot the points:

    for _ in range(num_steps):
        alpha = -(g / L) * np.sin(theta)  # Angular acceleration
        omega += alpha * dt  # Update angular velocity
        theta += omega * dt  # Update angle
    
        # Append data for plotting
        angles.append(theta)
        times.append(time)
        time += dt
    
    # angles to cartesian coordinates
    x = [L * np.sin(angle) for angle in angles]
    y = [-L * np.cos(angle) for angle in angles]

    , and the controls for the plotting on the map:

    fig, ax = plt.subplots()
    ax.set_xlim([-L - 0.1, L + 0.1])  # Extend limits slightly for visualization
    ax.set_ylim([-L - 0.1, 0.1])
    ax.set_aspect('equal')  # Ensure the pendulum appears correctly scaled
    
    line, = ax.plot([], [], 'o-', lw=2)

    We then animate it and save it as a MP4 file.

    def update(frame):
        print(f"Frame: {frame}, x: {x[frame]}, y: {y[frame]}")
        line.set_data([0, x[frame]], [0, y[frame]])
        return line,
    
    
    # creating and saving animation
    anim = FuncAnimation(fig, update, frames=num_steps, interval=dt * 1000, blit=True, repeat=False)
    anim.save('pendulum2.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

    Here is all of the code all together if you want to save it. just make sure you have your deps installed.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    # Parameters
    g = 9.8  # gravity
    L = 1.0  # length of pendulum
    theta = np.pi / 4  # starting angle (in radians)
    omega = 0  # initial angular velocity
    dt = 0.01  # time step (in seconds)
    
    # Simulation variables
    angles = []  # List to store angles
    times = []  # List to store time steps
    
    # Initial conditions
    time = 0.0
    num_steps = 1000  # Number of simulation steps
    
    # Simulate pendulum motion
    for _ in range(num_steps):
        alpha = -(g / L) * np.sin(theta)  # Angular acceleration
        omega += alpha * dt  # Update angular velocity
        theta += omega * dt  # Update angle
    
        # Append data for plotting
        angles.append(theta)
        times.append(time)
        time += dt
    
    # Convert angles to Cartesian coordinates
    x = [L * np.sin(angle) for angle in angles]
    y = [-L * np.cos(angle) for angle in angles]
    
    # plot setup
    fig, ax = plt.subplots()
    ax.set_xlim([-L - 0.1, L + 0.1])  # Extend limits slightly for visualization
    ax.set_ylim([-L - 0.1, 0.1])
    ax.set_aspect('equal')  # Ensure the pendulum appears correctly scaled
    
    line, = ax.plot([], [], 'o-', lw=2)  # Circle marker for pendulum mass
    
    
    # Animation update function
    def update(frame):
        print(f"Frame: {frame}, x: {x[frame]}, y: {y[frame]}")
        line.set_data([0, x[frame]], [0, y[frame]])
        return line,
    
    
    # creating and saving animation
    anim = FuncAnimation(fig, update, frames=num_steps, interval=dt * 1000, blit=True, repeat=False)
    anim.save('pendulum2.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

    I am going to visit hawaii tomorrow and let it be known I will be blogging some programming and studying I am doing from there, so I will see you all later :)

    iconLogo