Finding the Center of Mass from Point Masses with Python
Finding the Center of Gravity(CG) of a point mass in 1, 2 and 3 Dimensions¶
First, import python modules and set up the plotting
In [21]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
When using ipython notebooks, plotting inline can be achieved by execute the matplotlib magic function
In [22]:
%matplotlib inline
In [23]:
#set plot sizes
plt.rcParams['figure.figsize'] = (10, 2) # (width, height)
plt.rcParams['font.size'] = 20
plt.rcParams['legend.fontsize'] = 16
First, lets determine the CG of a 1D space¶
Lets randomly assign an x coordinate value for the point mass from [-50, 50] with n=20
In [24]:
n=20
x = np.random.randint(-50, 50, n)
print x
Now, assign 20 random mass's to the x points on a line from [1, 100]
In [25]:
m = np.random.randint(1,200, n)
print m
Since this is a 1 dimensional problem, y is the same for all x coordinates
In [26]:
y = np.zeros(len(m))
The calculation of a 1 dimensional CG can be done as follows
$$ \bar{x}=\frac{\sum_{i=0}^{n}{x_i*m_i}}{\sum_{i=0}^{n}{m_i}} $$In python, this can be represented as
In [27]:
cgx = np.sum(x*m)/np.sum(m)
print('The center of mass in x is %f' % cgx)
In [28]:
plt.scatter(x,y,s=m);
plt.scatter(cgx, 0, color='k', marker='|', s=1e4);
plt.gca().set_yticks([]) ;
plt.title('1 Dimensional Center of Gravity');
Now, lets determine the CG of a 2D space¶
Lets add a 2nd dimension, on the y axis
In [29]:
y = np.random.randint(0,200,n)
for a 2 dimension space, we need to find x and y seperatley, which will be our coordinates
$$ \bar{x}=\frac{\sum_{i=0}^{n}{x_i*m_i}}{\sum_{i=0}^{n}{m_i}} $$$$ \bar{y}=\frac{\sum_{i=0}^{n}{x_i*m_i}}{\sum_{i=0}^{n}{m_i}} $$In [30]:
cgy = np.sum(y*m)/np.sum(m)
print('The center of mass in y is %f' % cgy)
In [31]:
plt.rcParams['figure.figsize'] = (6, 10) # (width, height)
plt.scatter(x,y,s=m);
plt.scatter(cgx, cgy, color='k', marker='+', s=1e4);
plt.title('2 Dimensional Center of Gravity');
Finally, lets determine the CG of a 3D space¶
Lets add a 3rd dimension, on the z axis.
In [36]:
z = np.random.randint(0,30,n)
In [37]:
cgz = np.sum(z*m)/np.sum(m)
print('The center of mass is %f' % cgz)
execute %matplotlib qt
if you want to view an interactive 3d plot
In [38]:
# %matplotlib qt
In [35]:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, s=m);
ax.scatter(cgx, cgy, cgz, color='k', marker='+', s=1e4);
plt.title('3 Dimensional Center of Gravity');
In [ ]:
Comments
Comments powered by Disqus