Learn by doing it the other way round.
- import numpy
- class Particles:
- """ Sum of products of particle masses"""
- def __init__(self, l1, l2):
- self.l1 = l1
- self.l2 = l2
- N = len(l1)
- self.result = numpy.zeros(N) #No repetition N*(N-1)
- self.Total = 0
- def First_sums(self):
- l1, l2, ith_sums, Total = self.l1, self.l2, self.result, self.Total
- for i in range(0, (len(l1))):
- for j in range(0, len(l2)):
- ith_sums[i] += l1[i]*l2[j]
- for k in range(0, len(ith_sums)): # We can use Total = sum(ith_sums) here
- Total += ith_sums[k]
- return Total
- def Second_sums(self):
- l1, l2, ith_sums, Total = self.l1, self.l2, self.result, self.Total
- for i in range(0, (len(l1))):
- for j in range(0, len(l2)):
- if i == j:
- ith_sums[i] += l1[i]*l2[j]
- for k in range(0, len(ith_sums)):
- Total += ith_sums[k]
- return Total
- #def Differences(self): You can create another method to compute the difference
- #Demo
- if __name__ == '__main__':
- N = 1000000 #Define N
- list1 = list2 = numpy.random.randn(N) #list = [1,2,3,4,5], Try something simple
- p = Particles(list1, list2)
- y = Particles(list1, list2)
- sum1 = p.First_sums()
- sum2 = y.Second_sums()
- diff = sum1 - sum2
- print ("The difference between the two sums:", diff )
- #Try the following, and see what happens:
- #print ("The difference between the two sums:", p.First_sums() - p.Second_sums())