Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import math
  2. import random
  3.  
  4. import matplotlib.pyplot as plt
  5.  
  6.  
  7. def calc_ratio(r, n):
  8. in_points = []
  9. out_points = []
  10. for i in range(n):
  11. point = (random.uniform(-r, r), random.uniform(-r, r))
  12. distance = math.sqrt((point[0]) ** 2 + point[1] ** 2)
  13. if distance < r:
  14. in_points.append(point)
  15. else:
  16. out_points.append(point)
  17. ratio = len(in_points) / n
  18. return ratio, in_points, out_points
  19.  
  20.  
  21. R = 10
  22. N = 10000
  23. results = calc_ratio(R, N)
  24. print("The ratio of the areas of a circle and the square inscribing it is:")
  25. print(results[0])
  26.  
  27. fig = plt.figure(figsize=(11, 5))
  28.  
  29. plt.subplot(121)
  30. plt.xlim(-R, R)
  31. plt.ylim(-R, R)
  32. plt.title("Areas R=%s N=%s" % (R, N))
  33. plt.xlabel("R")
  34. plt.ylabel("R")
  35. plt.scatter(*zip(*results[1]), color='orange', alpha=0.5)
  36. plt.scatter(*zip(*results[2]), color='purple', alpha=0.5)
  37.  
  38. x1 = range(100, N + 100, 100)
  39. x2 = range(1, R + 1, 1)
  40. y1 = [calc_ratio(R, i)[0] for i in x1]
  41. y2 = [calc_ratio(i, N)[0] for i in x2]
  42. ax1 = fig.add_subplot(122)
  43. ax2 = ax1.twiny()
  44. line1, = ax1.plot(x1, y1, c='blue')
  45. line2, = ax2.plot(x2, y2, c='red')
  46. plt.ylim(0.6, 1.0)
  47. ax1.set_xlabel("N")
  48. ax2.set_xlabel("R")
  49. ax1.set_xlim(100, N)
  50. ax2.set_xlim(1, R)
  51. plt.legend((line1, line2), ("N", "R"))
  52. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement