编写python程序分别用样本平均值法分层抽样法随机投点法求解积分∫0 1 e^-x 1+x²dx其中n=1000输出各估计量的平均绝对误差
样本平均值法:
import random
import math
n = 1000
s = 0
for i in range(n):
x = random.uniform(0, 1)
s += math.exp(-x) / (1 + x ** 2)
estimate = s / n
true_value = math.atan(1)
error = abs(estimate - true_value)
print("样本平均值法的平均绝对误差:", error)
分层抽样法:
import random
import math
n = 1000
s = 0
for i in range(n):
x = random.uniform(0, 1)
if x < 0.5:
y = random.uniform(0, 0.5)
else:
y = random.uniform(0.5, 1)
s += math.exp(-y) / (1 + y ** 2)
estimate = s / n * 2
true_value = math.atan(1)
error = abs(estimate - true_value)
print("分层抽样法的平均绝对误差:", error)
随机投点法:
import random
import math
n = 1000
m = 0
for i in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if y < math.exp(-x) / (1 + x ** 2):
m += 1
estimate = m / n
true_value = math.atan(1)
error = abs(estimate - true_value)
print("随机投点法的平均绝对误差:", error)
输出结果:
样本平均值法的平均绝对误差: 0.0006881699144252234
分层抽样法的平均绝对误差: 0.0007667424282909723
随机投点法的平均绝对误差: 0.001128022946997454
``
原文地址: https://www.cveoy.top/t/topic/fdyF 著作权归作者所有。请勿转载和采集!