简体   繁体   English

生成 for 循环以计算具有不同样本量的 montecarlo 积分的误差

[英]Producing for loop to compute errors for montecarlo integration with different sample sizes

Basically, I'm trying to create a for loop which computes the estimates and errors for the integral below for different sample sizes.:基本上,我正在尝试创建一个 for 循环,该循环针对不同的样本量计算以下积分的估计值和误差。:

在此处输入图像描述

This is the code for a single calculation:这是单次计算的代码:

import numpy as np
truetheta = 0.2

m = 10000

x = np.random.uniform(0, 1, m)

y = (x)**4
naive = (np.sum(y)/m)
error = abs(naive - truetheta)

However, I want to produce one error for M = 2^i, with i = 1, 2, ... 10但是,我想为 M = 2^i 产生一个错误,其中 i = 1、2、... 10

My attempt looks as follows:我的尝试如下所示:

N = 10
sample_size = np.zeros(N)

# for loop creates sample size 2, 4, 8, 16 ....1024
for n in range(N):
    sample_size[n] = 2**(n+1)



# store output
naive = []
errornaive = []

# for-loop to compute error for different sample sizes
for i in (int(sample_size)):
    m = 2**i
    x = np.random.uniform(0, 1, m)
    y = x**4
    naive[i] = (np.sum(y)/m)
    errornaive[i] = abs(naive - truetheta)

When i run the code i get the error:当我运行代码时出现错误:

TypeError: only size-1 arrays can be converted to Python scalars TypeError: only size-1 arrays 可以转换为 Python 标量

I'm not really sure how to work around this issue, or whether the remainder of the loop is sound.我不太确定如何解决这个问题,或者循环的其余部分是否合理。 So i'm asking for a bit of assistance here, could someone offer a solution to my error message?所以我在这里寻求一些帮助,有人可以为我的错误消息提供解决方案吗? and 2, does anyone have a better suggestion than mine to perform the calculation?和 2,有没有人比我有更好的建议来执行计算?

Best regards and thanks in advance.最诚挚的问候和感谢。

With the help of some very helpful comments I managed to create the following code:在一些非常有用的评论的帮助下,我设法创建了以下代码:

N = 20
sample_size = np.zeros(N, dtype=int)

# for loop creates sample size 2, 4, 8, 16 ....1024
for n in range(N):
    sample_size[n] = 2**(n+1)



# store our output
naive = []

# for loop to compute error for different sampel sizes
for i in (sample_size):
    m = i
    x = np.random.uniform(0, 1, m)
    y = x**4
    naive.append(np.sum(y)/m)
 
# convert to array and get errors
naivearray = np.array(naive)
naiveerror = abs(naivearray - truetheta)

This runs without errors, but it's not pretty.这运行没有错误,但它并不漂亮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM