Alex H
Alex H

Reputation: 69

How to get a phase plot of a hamiltonian harmonic oscillator in Python?

I am trying to achieve a plot like this, but with multiple circles (where each circle represents the solved equation for a different energy/position/velocity): Phase Plot

Using this code:

import matplotlib.pyplot as plt
import numpy as np

def harmonic_oscillator_energy_force(x,k=1,x0=0):
    #calculate the energy on force on the right hand side of the equal signs
    energy = 0.5*k*(x-x0)**2
    force = -k*(x-x0)
    return energy, force

# phi changes the phase
def harmonic_oscillator_position_velocity(t, A=1, omega=1, phi=0):
    position = A * np.cos(omega * t + phi)
    velocity = -A * omega * np.sin(omega * t + phi)
    return position, velocity

    # this function will plot the energy and force for a harmonic oscilator
def plot_harmonic_oscillator(t_max=10, dt=0.1): #**kwargs):
    t_points = np.arange(0, t_max + dt, dt)
    for phi in range(-20, 20):
        for t in range(0, 100):
            position, velocity = harmonic_oscillator_position_velocity(t, 1, 1, phi)
            plt.plot(position, velocity)

plot_harmonic_oscillator(t_max=10, dt=0.1)
plt.show()

But it seems not to want to work ! I'm a beginner and would appreciate any help.

Upvotes: 1

Views: 1057

Answers (1)

Jiangyan Yang
Jiangyan Yang

Reputation: 36

I am also beginner, but I tried to add a b. into your plot function, please see as following:

plt.plot(position, velocity,**'b.'**)

then I got the figure: enter image description here

Upvotes: 1

Related Questions