I have got some code that calculates the angle between all of the points in an array. It works, but it is quite slow. This is because it has complexity O(n^2). It has to loop through the array and apply the
angle function to every combination of points.
import math import random def angle(pos1,pos2): dx=pos2-pos1 dy=pos2-pos1 rads=math.atan2(dy,dx) rads%=2*math.pi degs=math.degrees(rads) return degs class Point(object): def __init__(self): self.pos=[random.randint(0,500) for _ in range(2)]#random x,y self.angles= points=[Point() for _ in range(100)] for point in points: point.angles= #so that each frame, they will be recalculated for otherC in points: if otherC is point:continue #don't check own angle ang=angle(point.pos,otherC.pos) point.angles.append(ang)
I feel like it could be greatly sped up by using numPy or some other method. I did some searching (here), but all I could find was functions to get angle between planes, or complex numbers. I just need simple arrays. How can this code be optimized for more speed?