C++标准库--正态分布类 std::normal_distribution

参考链接:https://en.cppreference.com/w/cpp/numeric/random/normal_distribution

std::normal_distribution是C++11提供的一个正态分布函数模板类

头文件:include<random>

可以创建一个有特定期望值和方差的正态分布;

double mu {50.0}, sigma {10.0};
std::normal_distribution<> norm {mu, sigma};

下面是优达学城粒子滤波部分的一个案例,根据GPS提供初始值,初始化符合正态分布的粒子初值;

/**
 * print_samples.cpp
 * 
 * Print out to the terminal 3 samples from a normal distribution with
 * mean equal to the GPS position and IMU heading measurements and
 * standard deviation of 2 m for the x and y position and 0.05 radians
 * for the heading of the car. 
 *
 * Author: Tiffany Huang
 */

#include <iostream>
#include <random> // Need this for sampling from distributions

using std::normal_distribution;

/**
 * Prints samples of x, y and theta from a normal distribution
 * @param gps_x   GPS provided x position
 * @param gps_y   GPS provided y position
 * @param theta   GPS provided yaw
 */
void printSamples(double gps_x, double gps_y, double theta);


int main() {
  
  // Set GPS provided state of the car.
  double gps_x = 4983;
  double gps_y = 5029;
  double theta = 1.201;
  
  // Sample from the GPS provided position.
  printSamples(gps_x, gps_y, theta);
  
  return 0;
}


void printSamples(double gps_x, double gps_y, double theta) {
  std::default_random_engine gen;
  double std_x, std_y, std_theta;  // Standard deviations for x, y, and theta

  // TODO: Set standard deviations for x, y, and theta
    std_x = 2;
    std_y = 2;
    std_theta = 0.5;

  // This line creates a normal (Gaussian) distribution for x
    normal_distribution<double> dist_x(gps_x, std_x);
  
  // TODO: Create normal distributions for y and theta
    normal_distribution<double> dist_y(gps_y, std_y);
    normal_distribution<double> dist_theta(theta, std_theta);

  for (int i = 0; i < 10; ++i) {
    double sample_x, sample_y, sample_theta;
    
    // TODO: Sample from these normal distributions like this: 
    //   sample_x = dist_x(gen);
    //   where "gen" is the random engine initialized earlier.
    sample_x = dist_x(gen);
    sample_y = dist_y(gen);
    sample_theta = dist_theta(gen);
    
    // Print your samples to the terminal.
    std::cout << "Sample " << i + 1 << " " << sample_x << " " << sample_y << " " 
              << sample_theta << std::endl;
  }

  return;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值