基本上,我试图创建一个for循环,它计算不同样本大小的积分的估计值和误差。
这是单个计算的代码:
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)
但是,我想为M= 2^i生成一个错误,其中i= 1,2,. 10
我的尝试如下:
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)
当我运行代码时,我得到了错误:
TypeError:只有size-1数组可以转换为Python标量。
我不太确定如何解决这个问题,或者循环的其余部分是否正常。所以我在这里请求一些帮助,有人能为我的错误信息提供一个解决方案吗?有没有人比我有更好的建议来做这个计算?
提前向您致以最良好的问候和感谢。
发布于 2022-10-09 02:24:25
在一些非常有用的注释的帮助下,我成功地创建了以下代码:
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)
它运行时没有错误,但并不好看。
https://stackoverflow.com/questions/74001462
复制相似问题