The Python Book
 
collinear point
20151022

Generate an array of collinear points plus some random points

  • generate a number of points (integers) that are on the same line
  • randomly intersperse these coordinates with a set of random points
  • watchout: may generate dupes! (the random points, not the collinear points)

Source:

import random

p=[(5,5),(1,10)]    # points that define the line 

# warning: this won't work for vertical line!!!
slope= (float(p[1][1])-float(p[0][1]))/(float(p[1][0])-float(p[0][0]) )
intercept= float(p[0][1])-slope*float(p[0][0])

ar=[]
for x in range(0,25):     
    y=slope*float(x)+intercept

    # only keep the y's that are integers
    if (y%2)==0: 
        ar.append((x,int(y)))
    
    # intersperse with random coordinates
    r=3+random.randrange(0,5)  

    # only add random points when random nr is even
    if r%2==0: 
        ar.extend( [ (random.randrange(0,100),random.randrange(0,100)) for j in range(r) ])  
    
print ar

Sample output:

[(1, 10), (97, 46), (94, 12), (33, 10), (9, 71), (9, 0), (28, 34), 
(2, 94), (30, 29), (69, 28), (82, 31), (79, 86), (88, 46), (59, 24), 
(2, 78), (54, 88), (94, 78), (99, 37), (75, 48), (91, 1), (67, 61), 
(12, 11), (55, 55), (58, 82), (95, 99), (56, 27), (12, 18), (99, 25), 
(77, 84), (31, 39), (64, 84), (4, 13), (80, 63), (43, 27), (78, 43), 
(24, 32), (17, -10), (73, 15), (6, 97), (0, 74), (16, 97), (6, 77), 
(60, 77), (19, 83), (19, 82), (19, 40), (58, 63), (64, 62), (14, 53),
(57, 21), (49, 24), (66, 94), (82, 1), (29, 39), (55, 64), (85, 68), 
(39, 24)]
 
Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22