#!/usr/bin/env python # coding: utf-8 # # [Homework Week 6](https://tsoo-math.github.io/ucl2/2021-HW-week6.html) # # For complete written solutions, please [see](https://tsoo-math.github.io/ucl/QHW1-sol.html). We will mainly be concerned with the Python code here. # ## Integration # In[1]: import numpy as np def g(x): # defines the function g y=np.power(x,2) * np.sin(x) return y z = np.random.exponential(scale=1.0, size=10000) # simulates 10000 iid exp integralapprox = np.average(g(z)) # approximation using the law of large numbers print(integralapprox) # ## Grouping coins # In[2]: def isFour(x): # function which checks if the binary sequence has a run of four heads ans =0 for i in range(len(x) +1-4 ): if (x[i]==1 and x[i+1]==1 and x[i+2]==1 and x[i+3]==1): ans=1 return ans def check(): # checking if a single random binary sequence of length 20 has a run of four heads binseq = np.random.binomial(1, 0.5, 20) return isFour(binseq) num = [check() for _ in range(10000)] # run the check function 10000 times print(np.average(num)) # ## Pen and paper # In[3]: def T(): s=0 n=0 while s<1: s = s + np.random.uniform() n=n+1 return n num = [T() for _ in range(100000)] print(np.average(num)) # ## Endnotes # # Use the ipynb [source](https://tsoo-math.github.io/ucl2/2021-hw-week6.ipynb) for the most update version. # In[4]: from datetime import datetime print(datetime.now())