HomoCivicus

Task 3

May 16th, 2020
1,418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. number_of_iterations = 300000
  5. number_of_triangles = 3
  6. triangles = np.random.rand(number_of_triangles, 3, 2)
  7. points_of_intersection = []
  8.  
  9. for index in range(number_of_iterations):
  10.     point = np.array([np.random.rand() for i in range(2)])
  11.    
  12.     coefficients = np.array([[(triangle[0][0] - point[0]) * \
  13.                               (triangle[1][1] - triangle[0][1]) - \
  14.                               (triangle[1][0] - triangle[0][0]) * \
  15.                               (triangle[0][1] - point[1]), \
  16.                               (triangle[1][0] - point[0]) * \
  17.                               (triangle[2][1] - triangle[1][1]) - \
  18.                               (triangle[2][0] - triangle[1][0]) * \
  19.                               (triangle[1][1] - point[1]), \
  20.                               (triangle[2][0] - point[0]) * \
  21.                               (triangle[0][1] - triangle[2][1]) - \
  22.                               (triangle[0][0] - triangle[2][0]) * \
  23.                               (triangle[2][1] - point[1])] \
  24.                              for triangle in triangles])
  25.  
  26.     number_of_intersections = 0
  27.    
  28.     for cur_coefs in coefficients:
  29.         if np.all(cur_coefs > 0) or np.all(cur_coefs < 0):
  30.             number_of_intersections += 1
  31.    
  32.     if number_of_intersections >= 2:
  33.         points_of_intersection.append(point)
  34.  
  35. points_of_intersection = np.array(points_of_intersection)
  36. ax = plt.gca()  
  37.  
  38. for triangle in triangles:
  39.     ax.fill([point[0] for point in triangle], [point[1] for point in triangle])
  40.  
  41. plt.scatter([point[0] for point in points_of_intersection], \
  42.             [point[1] for point in points_of_intersection], \
  43.             s=1, zorder=2)
  44.  
  45. print(f'The approximate area of intersections is {len(points_of_intersection) / number_of_iterations}')
Add Comment
Please, Sign In to add comment