Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- Created on Thu Oct 17 12:34:11 2019
- @author: gullholm
- """
- import random
- import numpy as np
- import matplotlib.pyplot as plt
- theta = 0
- M = 10000
- #question 2
- for i in range((M-1)):
- U = random.uniform(0,1)
- theta += U**2
- print(2*theta/M, "question 2")
- # Question 3
- theta = 0
- count = 0
- for i in range((M-1)):
- U_1 = random.uniform(0,1)
- U_2 = random.uniform(0,1)
- if U_2 < (U_1**2):
- count += 1
- print(float(2*count)/float(M),"Question 3")
- # Question 5
- theta = 0
- N = 1000
- theta_2 = 0
- crude = [0]*N
- HM = [0]*N
- for j in range((N-1)):
- theta_2=0
- count = 0
- for i in range((M-1)):
- U_1 = np.random.uniform(0,1)
- U_2 = np.random.uniform(0,1)
- theta_2 += U_1**2
- if U_2 <= (U_1**2):
- count += 1
- crude[j+1] = 2*(theta_2/M)
- HM[j+1] = 2*(float(count)/M)
- #crude
- print(float(16)/float(45))
- print(np.var(crude), "var Crude")
- #HM
- print(np.sqrt(np.var(HM)), "RMSE HM")
- # question 6
- N = 20
- sample_size = np.zeros(N)
- err_HM = np.zeros(N)
- err_crude = np.zeros(N)
- for n in range(N):
- sample_size[n] = 2**(n+1)
- for i in range((N)):
- M = 2**(i+1)
- theta_2 = 0
- count = 0
- for m in range((M-1)):
- U_1 = np.random.uniform(0,1)
- U_2 = np.random.uniform(0,1)
- theta_2 += U_1**2
- if U_2 <= (U_1**2):
- count += 1
- err_crude[i] = np.abs((2*(theta_2)/M)-(2/3))
- err_HM[i] = np.abs((2*(float(count)/M))-(2/3))
- plt.loglog(sample_size, (sample_size)**(-0.5))
- plt.loglog(sample_size,err_crude)
- plt.loglog(sample_size, err_HM)
- #err_HM = np.zeros(N)
- #err_crude = np.zeros(N)
- #average_1 = 0
- #for m in range(int(sample_size[N-1])):
- # U_1 = np.random.uniform(0,1)
- # U_2 = np.random.uniform(0,1)
- # theta_2 += U_1**2
- # if U_2 <= (U_1**2):
- # count += 1
- # for n in range(N):
- # if m==(int(sample_size[n])-1):
- ## err_crude[n] = np.abs(2*(theta_2/sample_size[n])-(2/3))
- # err_HM[n] = np.abs(2*(float(count)/sample_size[n])-(2/3))
- # theta_2=0
- # count=0
- #print(err_HM)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement