重要性抽样c++实现代码
时间: 2023-10-29 20:07:12 浏览: 34
重要性抽样(Importance Sampling)是一种用于估计分布中期望值的统计方法,通常用于概率计算、机器学习、物理仿真等领域。下面是C++实现代码:
```
#include <iostream>
#include <random>
using namespace std;
double target_distribution(double x) {
// 定义目标分布,这里以标准正态分布为例
return exp(-x * x / 2) / sqrt(2 * M_PI);
}
double proposal_distribution(double x) {
// 定义建议分布,这里以均值为0,标准差为1的正态分布为例
return exp(-x * x / 2) / sqrt(2 * M_PI);
}
double importance_sampling(int n) {
// n为采样次数
random_device rd;
mt19937 gen(rd());
normal_distribution<> proposal(0, 1);
double sum = 0;
for (int i = 0; i < n; i++) {
double x = proposal(gen);
double w = target_distribution(x) / proposal_distribution(x); // 计算权重
sum += w;
}
return sum / n;
}
int main() {
int n = 100000;
double estimate = importance_sampling(n);
cout << "重要性抽样估计值:" << estimate << endl;
return 0;
}
```
其中,`target_distribution`表示目标分布函数,`proposal_distribution`表示建议分布函数,`importance_sampling`表示重要性抽样函数,`n`为采样次数,`proposal`为建议分布的随机数生成器,`sum`为加权和,`w`为权重,最后返回加权平均值。在本例中,我们采用均值为0,标准差为1的正态分布作为建议分布。