# 利用有放回抽样估计自然常数e python

### 利用有放回抽样估计自然常数e python

lim

n

(

1

1

n

)

n

=

1

e

lim_{n to infty} (1-frac{1}{n} )^n=frac{1}{e}

nlim(1n1)n=e1

#### 代码

import pandas as pd
import numpy as np
import time
time_start = time.time()  # 记录开始时间
d={}
n=10000000
cnt=0
for i in range(n):
num=random.randint(0,n-1)
if d.get(num,0)==0:
d[num]=1
else:
cnt=cnt+1
print(n/cnt)
time_end = time.time()  # 记录结束时间
time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
print(time_sum)


numpy版

import pandas as pd
import numpy as np
import time
time_start = time.time()  # 记录开始时间
n=10000000
d=np.zeros(n, dtype = int)
cnt=0
for i in range(n):
num=random.randint(0,n-1)
if d[num]==0:
d[num]=d[num]+1
else:
d[num]=d[num]+1
cnt=cnt+1
print(n/cnt)
time_end = time.time()  # 记录结束时间
time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
print(time_sum)


set版

import pandas as pd
import numpy as np
import time
time_start = time.time()  # 记录开始时间
n=10000000
d=set()
for i in range(n):
num=random.randint(0,n-1)