【C++】13 多元正态分布抽样

目的

2022/4/28

用C++实现多元正态分布抽样

本地目录:E:\Master\study\Cpp\MultivariateNormalDistributionSamples

参考资料

[1]https://ros-developer.com/2017/11/15/generating-multivariate-normal-distribution-samples-using-c11-eigen-library/

[2]https://github.com/beniz/eigenmvn

[3]http://arma.sourceforge.net/

[4]http://arma.sourceforge.net/docs.html#mvnrnd

思路

在R语言中可以轻松调用rmvnorm()函数实现从多元正态分布中抽样,我希望在C++中实现这种功能。经过一番搜索,找到两种方法。

  • 使用Armadillo库的mvnrnd()函数[3-4]
  • 使用Eigen库自行编写[1-2]

使用Armadillo

使用vcpkg安装Armadillo

E:\software\vcpkg目录下,右键,在终端中打开,输入命令

./vcpkg install Armadillo

等待漫长的下载安装过程,即可安装完成32位Armadillo

再输入命令

./vcpkg install Armadillo:x64-windows

等待漫长的下载安装过程,即可安装完成64位Armadillo

使用Eigen库自行编写

该方法较为复杂,经过试验,放弃使用

源码

在VS2019中,输入以下代码,编译链接

// MultivariateNormalDistributionSamples.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// 参考资料:http://arma.sourceforge.net/
// https://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c


#include <iostream>
#include <armadillo>//包含armadillo头文件

using namespace std;
using namespace arma;//armadillo命名空间

int main()
{
	cout << "Armadillo version: " << arma_version::as_string() << endl;

	mat A = randu<mat>(4, 5);//4行5列矩阵
	mat B = randu<mat>(4, 5);

	cout << "A*B.t():\n" << A * B.t() << endl;//.t()向量或矩阵转置

	(A * B.t()).print("A*B.t():");

	vec M(5, fill::randu);

	mat D(5, 5, fill::randu);
	mat C = D.t() * D;

	mat X = mvnrnd(M, C, 5);

	cout << "X:\n" << X << endl;

	system("pause");

	return 0;
}

运行结果

Armadillo version: 10.6.2 (Keep Calm)
A*B.t():
   1.0269   1.0702   1.3516   1.9736
   1.0553   1.6784   1.7857   1.7695
   0.5042   0.4844   0.5324   1.0123
   0.6624   1.3403   1.2322   1.2464

A*B.t():
   1.0269   1.0702   1.3516   1.9736
   1.0553   1.6784   1.7857   1.7695
   0.5042   0.4844   0.5324   1.0123
   0.6624   1.3403   1.2322   1.2464
X:
   2.1518  -1.9524  -1.3810   0.4499  -0.5635
   2.5495  -2.1896  -2.4168  -0.1311  -0.6948
   3.1666  -0.0019   0.4300  -0.1362   0.8860
   4.2867  -1.7698  -0.2368   0.3843   0.3144
   1.8961  -0.4027   0.5270   1.2690   0.4838

请按任意键继续. . .
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卢家波

如果对你有帮助,请我喝杯茶吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值