WPILibC++ 2027.0.0-alpha-4
Loading...
Searching...
No Matches
Normal.hpp
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <array>
8#include <concepts>
9#include <random>
10#include <span>
11
12#include <Eigen/Core>
13
16
17namespace wpi::math {
18
19/**
20 * Creates a vector of normally distributed random values with the given
21 * standard deviations for each element.
22 *
23 * @param stdDevs An array whose elements are the standard deviations of each
24 * element of the random vector.
25 * @return Vector of normally distributed values.
26 */
27template <std::same_as<double>... Ts>
28Eigen::Vector<double, sizeof...(Ts)> Normal(Ts... stdDevs) {
29 std::random_device rd;
30 std::mt19937 gen{rd()};
31
32 Eigen::Vector<double, sizeof...(Ts)> result;
34 [&](int i, double stdDev) {
35 // Passing a standard deviation of 0.0 to std::normal_distribution is
36 // undefined behavior
37 if (stdDev == 0.0) {
38 result(i) = 0.0;
39 } else {
40 std::normal_distribution distr{0.0, stdDev};
41 result(i) = distr(gen);
42 }
43 },
44 stdDevs...);
45 return result;
46}
47
48/**
49 * Creates a vector of normally distributed random values with the given
50 * standard deviations for each element.
51 *
52 * @param stdDevs An array whose elements are the standard deviations of each
53 * element of the random vector.
54 * @return Vector of normally distributed values.
55 */
56template <int N>
57Eigen::Vector<double, N> Normal(const std::array<double, N>& stdDevs) {
58 std::random_device rd;
59 std::mt19937 gen{rd()};
60
61 Eigen::Vector<double, N> result;
62 for (size_t i = 0; i < stdDevs.size(); ++i) {
63 // Passing a standard deviation of 0.0 to std::normal_distribution is
64 // undefined behavior
65 if (stdDevs[i] == 0.0) {
66 result(i) = 0.0;
67 } else {
68 std::normal_distribution distr{0.0, stdDevs[i]};
69 result(i) = distr(gen);
70 }
71 }
72 return result;
73}
74
75/**
76 * Creates a vector of normally distributed random values with the given
77 * standard deviations for each element.
78 *
79 * @param stdDevs A possibly variable length container whose elements are the
80 * standard deviations of each element of the random vector.
81 * @return Vector of normally distributed values.
82 */
83WPILIB_DLLEXPORT Eigen::VectorXd Normal(const std::span<const double> stdDevs);
84
85} // namespace wpi::math
#define WPILIB_DLLEXPORT
Definition SymbolExports.hpp:36
Definition LinearSystem.hpp:20
Eigen::Vector< double, sizeof...(Ts)> Normal(Ts... stdDevs)
Creates a vector of normally distributed random values with the given standard deviations for each el...
Definition Normal.hpp:28
constexpr void for_each(F &&f, Ts &&... elems)
Calls f(i, elem) for each element of elems where i is the index of the element in elems and elem is t...
Definition Algorithm.hpp:29