• Active Topics 

Python Classes - sum of products

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: 5211
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#1

This simple implementation of Python class program calculates products of random masses of particles, using the formula . The idea is that, you generate random masses of particles, take the products between them but without multiplying mass of a particle by itself and then sum up all the products, the number of products is given by (prove this).

Learn by doing it the other way round.
  1. import numpy
  2.  
  3. class Particles:
  4.  
  5.     """ Sum of products of particle masses"""
  6.  
  7.     def __init__(self, l1, l2):
  8.         self.l1 = l1
  9.         self.l2 = l2
  10.         N = len(l1)
  11.         self.result = numpy.zeros(N) #No repetition N*(N-1)
  12.         self.Total = 0
  13.     def First_sums(self):
  14.         l1, l2, ith_sums, Total = self.l1, self.l2, self.result, self.Total
  15.         for i in range(0, (len(l1))):
  16.             for j in range(0, len(l2)):
  17.                 ith_sums[i] += l1[i]*l2[j]
  18.         for k in range(0, len(ith_sums)):  # We can use Total = sum(ith_sums) here
  19.             Total += ith_sums[k]
  20.         return Total
  21.  
  22.     def Second_sums(self):                                              
  23.         l1, l2, ith_sums, Total = self.l1, self.l2, self.result, self.Total        
  24.         for i in range(0, (len(l1))):
  25.             for j in range(0, len(l2)):
  26.                 if i == j:
  27.                     ith_sums[i] += l1[i]*l2[j]
  28.         for k in range(0, len(ith_sums)):
  29.             Total += ith_sums[k]
  30.         return Total
  31. #def Differences(self): You can create another method to compute the difference
  32. #Demo
  33. if __name__ == '__main__':
  34.     N = 1000000 #Define N
  35.     list1 = list2 = numpy.random.randn(N) #list = [1,2,3,4,5], Try something simple                  
  36.     p = Particles(list1, list2)
  37.     y = Particles(list1, list2)
  38.     sum1 = p.First_sums()
  39.     sum2 = y.Second_sums()
  40.     diff = sum1 - sum2
  41.     print ("The difference between the two sums:", diff )
  42.  
  43. #Try the following, and see what happens:
  44. #print ("The difference between the two sums:", p.First_sums() - p.Second_sums())

Learn to program in Python, post your code to share with others.
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 1 guest