Advertisement
Carlettos

23.b)

Oct 23rd, 2020
1,936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. import random as rnd
  2. import matplotlib.pyplot as plt
  3. import math
  4.  
  5.  
  6. def p(x, σ, μ):
  7.     return 1/(math.sqrt(2*math.pi)) * math.exp(-1/(2*σ**2) * (x-μ)**2)
  8.  
  9.  
  10. def aceptar(a, b, σ, μ):
  11.     xt = 0
  12.     while 1:
  13.         xt = rnd.random()*(b - a) + a
  14.         r = rnd.random()/(math.sqrt(2*math.pi))
  15.         if r < p(xt, σ, μ):
  16.             break
  17.     return xt
  18.  
  19.  
  20. n = 100_000
  21. b = 8
  22. a = -8
  23. σ = math.sqrt(1.5)
  24. μ = 2
  25. x = []
  26.  
  27. for i in range(n):
  28.     x.append(aceptar(a, b, σ, μ))
  29.  
  30. plt.subplot(2, 1, 1)
  31. plt.hist(x, 100)
  32. plt.ylabel("yo")
  33.  
  34. y = []
  35. for i in range(n):
  36.     y.append(rnd.normalvariate(μ, σ))
  37.  
  38. plt.subplot(2, 1, 2)
  39. plt.hist(y, 100)
  40. plt.ylabel("random::normalvariate")
  41. plt.show()
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement