Simple Python Class to calculate gravity between two objects

Including Cython, Jython, IronPython, PyPy, Django framework, and interpreters: Ipython, IPython Jupyter/Notebook, CPython


Post Reply
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5214
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#1

This is a simple implementation of Python class to calculate gravitational force between two objects, say the earth and moon.
  1. class Gravity:
  2.     """Gravitational force between two physical objects."""
  3.     def __init__(self, m, M):
  4.         self.m = m # mass of object 1
  5.         self.M = M   # mass of object 2
  6.         self.G = 6.67428E-11 # gravity constant, m**3/kg/s**2
  7.  
  8.     def force(self, r):
  9.         G, m, M = self.G, self.m, self.M
  10.         return G*m*M/r**2
  11.  
  12.     def visualize(self, r_start, r_stop, n=100):
  13.         from scitools.std import plot, linspace # Can use numpy.linspace
  14.         import matplotlib.pyplot as plt
  15.         r = linspace(r_start, r_stop, n)
  16.         g = self.force(r)
  17.         title='Gravity force: m=%g, M=%g' % (self.m, self.M)
  18.         plot(r, g, title=title)
  19.         fig = plt.figure()
  20.         fig.savefig("Nothing.png")
  21.         #plt.show()
  22. #Demo
  23. mass_moon = 7.35E+22; mass_earth = 5.97E+24
  24. gravity = Gravity(mass_moon, mass_earth)
  25. r = 3.85E+8 # Earth-Moon distance in meters
  26. Fg = gravity.force(r)
  27. print 'force:', Fg
  28.  
  29. Visualize = gravity.visualize(r-100,r, 100)

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply
  • Similar Topics
    Replies
    Views
    Last post

Return to “Python Programming”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests