user9436260
user9436260

Reputation:

Python odeint function doesn't seem to work

I want to study a charged particle's motion while travelling through a magnetic field by modelling it with Python. I tried to use odeint function from scipy.integrate and it doesn't seem to work as I expected. Here is what I expected given the initial condition:

Charged particle motion in a magnetic field

But here is what I got with my simulation:

The curve is not the way it should be

The problem comes from my implementation of the odeint function. Any help is apreciated.

Here is my code:

import numpy as np

import matplotlib.pyplot as plt

from scipy.integrate import odeint

from mpl_toolkits.mplot3d import Axes3D


def vect_prod(u, v):
    return np.array([u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]])


def dy(y, t):
    x1, Vx, y1, Vy, z1, Vz = y

    F = q * (E + vect_prod(np.array([Vx, Vy, Vz]), B))

    dy = [Vx, Vx - F[0] / m, Vy, Vy - F[1] / m, Vz, Vz - F[2] / m]


    return dy


E = np.array([0, 0, 0])

B = np.array([0, 0, 1])

q = 1

m = 1

a = 0.04

cond = [0, 1, 0, 1, 0, 1]

t = np.arange(0, 100, 0.1)

sol = odeint(dy, cond, t)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

plt.plot(sol[:, 0], sol[:, 2], sol[:, 4])

plt.show()

Any help will be appreciated!

Upvotes: 1

Views: 504

Answers (1)

HYRY
HYRY

Reputation: 97291

I think the mass is too large:

import numpy as np

import matplotlib.pyplot as plt

from scipy.integrate import odeint

from mpl_toolkits.mplot3d import Axes3D


def vect_prod(u, v):
    return np.array([u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]])


def dy(y, t):
    x1, Vx, y1, Vy, z1, Vz = y

    F = q * (E + vect_prod(np.array([Vx, Vy, Vz]), B))

    dy = [Vx, Vx - F[0] / m, Vy, Vy - F[1] / m, Vz, Vz - F[2] / m]


    return dy


E = np.array([0, 0, 0])

B = np.array([0, 0, 1])

q = 1

m = 0.001

a = 0.04

cond = [0, 1, 0, 1, 0, 1]

t = np.arange(0, 0.05, 0.0001)

sol = odeint(dy, cond, t)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

plt.plot(sol[:, 0], sol[:, 2], sol[:, 4])

plt.show()

the output:

enter image description here

Upvotes: 1

Related Questions