jukaukor

monte_carlo_pygameplot_pi.py

Mar 27th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. # Heitetään pisteitä satunnaisesti neliölle
  2. # Osa pisteistä osuu neliön sisällä olevalle neljännesympyrälle
  3. # Lasketaan tuloksista Piin arvo
  4. # Juhani Kaukoranta 27.3.2019
  5. import pygame
  6. import random
  7. import time
  8. # heitetään satunnaispisteitä ympyrän jonka keskellä on neliö
  9. # piirtoruudun koko 600,600
  10. # neliön koko keskellä 400,400
  11. # keskipiste 300,300
  12. width = 600
  13. height = 600
  14.  
  15. def monte_carlo_pi(n):
  16. accum = 0
  17. screen = pygame.display.set_mode((width, height))
  18. for i in range(n):
  19. x = random.randint(100,500)
  20. y = random.randint(100,500)
  21. pygame.display.flip()
  22. if ((x-300)**2 + (y-300)**2) < 40000 :
  23. screen.set_at((x, y), (255, 0, 0))
  24. accum += 1
  25. else :
  26. screen.set_at((x, y), (0, 0, 255))
  27. return 4.0*accum/n
  28. pisteita = int(input("Kuinka monta pistettä arvotaan "))
  29. time0 = time.perf_counter()
  30. print("Pii = ",monte_carlo_pi(pisteita))
  31. time1 = time.perf_counter()
  32. print("Aikaa kului ",time1-time0," sekuntia")
Advertisement
Add Comment
Please, Sign In to add comment