I have my function in Python for normal distribution. I need to convert it to C++ and i am not familiar with language.
Here is my Python:
def calculation(value):
sigma = 0.5
size = 10000
x = 200
x_distribution = np.random.normal(value, sigma, size)
for i in x_distribution:
x.append(i)
return x
And it works as expected. I am trying to re-write same thing in C++ and found only the Link and where the "std::normal_distribution<> d{5,2};
" has to make magic. But i could not figure it out how to implement.
Here what i have tried and it is failing.
# include frame.distribution
Frame DistributionModel(x_mu, x_sigma)
{
// Motion model;ignore it
model = std::normal_distribution<> d{x_mu,x_sigma};
return model;
}
Please, help me. Looking for any hints. Thanks.
Well, trouble without end...
# include frame.distribution
Syntax for inclusion is:
#include <name_of_header_file>
// or:
#include "name_of_header_file"
(The space in between # and include does not harm, but is absolutely uncommon...)
Frame DistributionModel(x_mu, x_sigma)
C++ is a strongly typed language, i. e. you cannot just give variables a name as in Python, but you need to give them a type!
Frame DistributionModel(double x_mu, double x_sigma)
Same for local variables; type must match what you actually assign to (unless using auto)
std::normal_distribution<double> nd(x_mu, x_sigma);
This is a bit special about C++: You define a local variable, e. g.
std::vector<int> v;
In case of a class, it gets already constructed using its default constructor. If you want to call a constructor with arguments, you just append the call to the variable name:
std::vector<int> v(10); // vector with 10 elements.
What you saw in the sample is a feature called "uniform initialisation", using braces instead of parentheses. I personally strongly oppose against its usage, though, so you won't ever see it in code I have written (see me constructing the std::normal_distribution above...).
std::normal_distribution is defined in header random, so you need to include it (before your function definition):
#include <random>
About the return value: You only can return Frame, if the data type is defined somewhere. Now before trying to define a new class, we just can use an existing one: std::vector (it's a template class, though). A vector is quite similar to a python list, it is a container class storing a number of objects in contiguous memory; other than python lists, though, the type of all elements stored must be the same. We can use such a vector to collect the results:
std::vector<double> result;
Such a vector can grow dynamically, however, this can result in necessity to re-allocate the internal storage memory. Costly. If you know the number of elements in advance, you can tell the vector to allocate sufficient memory in advance, too:
result.reserve(max);
The vector is what we are going to return, so we need to adjust the function signature (I allowed to give it a different name and added another parameter):
std::vector<double> getDistribution(double x_mu, double x_sigma, size_t numberOfValues)
It would be possible to let the compiler deduce the return type, using auto keyword for. While auto brings quite a lot of benefits, I do not recommend it for given purpose: With explicit return type, users of the function see right from the signature what kind of result to expect and do not have to look into the function body to know about.
std::normal_distribution now is a number generator; it does not deliver the entire sequence at once as the python equivalent does, you need to draw the values one by another explicitly:
while(numberOfValues-- > 0)
{
auto value = nd(gen);
result.push_back(value);
}
nd(gen): std::normal_distribution provides a function call operator operator(), so objects of can be called just like functions (such objects are called "functors" in C++ terminology). The function call, however, requires a random number generator as argument, so we need to provide it as in the example you saw. Putting all together:
#include <random>
#include <vector>
std::vector<double> getDistribution
(
double x_mu, double x_sigma, size_t numberOfValues
)
{
// shortened compared to your example:
std::mt19937 gen((std::random_device())());
// create temporary (anonymous) ^^
// instance and call it immediately ^^
// afterwards
std::normal_distribution<double> nd(x_mu, x_sigma);
std::vector<double> result;
result.reserve(numberOfValues);
while(numberOfValues-- > 0)
{
// shorter than above: using result of previous
// function (functor!) call directly as argument to next one
result.push_back(nd(gen));
}
// finally something familiar from python:
return result;
}
#include<iostream>
#include<random>
#include<chrono>
int main() {
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::normal_distribution<double> distribution(0.0, 3.0);
double number = abs(distribution(generator));
std::cout << number;
std::cin.get();
return 0;
}
This may help, create a random number using gaussian with mean=0.0 and std_dev= 3.0
Related
In my project there are few functions that return multiple values with the help of tuple and they are used numerously. So I just want to know is there any way in c++ with which I can capture and initialize individual values that are returned by that function call. Below example will explain this question better
#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string,int,int> getStringWithSizeAndCapacity()
{
std::string ret = "Hello World !";
return make_tuple(ret,ret.size(),ret.capacity());
}
int main()
{
//First We have to declare variable
std::string s;
int sz,cpcty;
//Then we have to use tie to intialize them with return of function call
tie(s,sz,cpcty) = getStringWithSizeAndCapacity();
std::cout<<s<<" "<<sz<<" "<<cpcty<<std::endl;
//Is there a way in which I can directly get these variables filled from function call
//I don't want to take result in std::tuple because get<0>,get<1> etc. decreases readibility
//Also if I take return value in tuple and then store that in individual variables then I am wasting
//tuple as it will not be used in code
return 0;
}
Is there a way in which I can directly get these variables filled from function call I don't want to take result in std::tuple because get<0>,get<1> etc. decreases readibility
Also if I take return value in tuple and then store that in individual variables then I am wasting tuple as it will not be used in code
I understand that the use of std::get<>() decreases readability, but you can try to improve it with some comments
// get the size of the returned string (position 1)
auto sz = std::get<1>(getStringWithSizeAndCapacity());
Anyway, it seems to me that the right way to improve readability is the use of std::tie(), and isn't clear to me what's wrong with it for you, or (starting from C++17) also structured binding declarations
auto [ s, sz, cpcty ] = getStringWithSizeAndCapacity();
If you want avoid to name unused variables (say you are not interested in capacity, by example) you can use std::ignore
std::string s;
int sz;
std::tie(s,sz,std::ignore) = getStringWithSizeAndCapacity();
Unfortunately std::ignore can't be used (as far I know) with new C++17 structured binding (maybe something similar from C++20?).
I'm just starting to use C++11's <random> header for the first time, but there are still some things that seem a bit mysterious. This question is about the intended, idiomatic, best-practice way to accomplish a very simple task.
Currently, in one part of my code I have something like this:
std::default_random_engine eng {std::random_device{}()};
std::uniform_int_distribution<> random_up_to_A {0, A};
std::uniform_int_distribution<> random_up_to_B {0, B};
std::uniform_int_distribution<> random_up_to_some_other_constant {0, some_other_constant};
and then when I want an integer between 0 and B I call random_up_to_B(eng).
Since this is starting to look a bit silly, I want to implement a function rnd such that rnd(n, eng) returns a random integer between 0 and n.
Something like the following ought to work
template <class URNG>
int rnd(int n, URNG &eng) {
std::uniform_int_distribution<> dist {0, n};
return dist(eng);
}
but that involves creating a new distribution object every time, and I get the impression that's not the way you're supposed to do it.
So my question is, what is the intended, best-practice way to accomplish this simple task, using the abstractions provided by the <random> header? I ask because I'm bound to want to do much more complicated things than this later on, and I want to make sure I'm using this system in the right way.
uniform_int_distribution should not be expensive to construct, so creating one every time with new limits should be OK. However, there is a way to use the same object with new limits, but it is cumbersome.
uniform_int_distribution::operator() has an overload that takes a uniform_int_distribution::param_type object which can specify the new limits to be used, but param_type itself is an opaque type, and there's no portable way to construct one except extracting it from an existing uniform_int_distribution instance. For instance, the following function can be used to construct a uniform_int_distribution::param_type.
std::uniform_int_distribution<>::param_type
make_param_type(int min, int max)
{
return std::uniform_int_distribution<>(min, max).param();
}
Pass these to operator() and the generated result will be in the specified range.
Live demo
So if you really want to reuse the same uniform_int_distribution, create and save multiple instance of param_type using the function above, and use these when calling operator().
The answer above is inaccurate, because the standard does specify that the param_type can be constructed from the same distribution arguments as those used by the corresponding distribution type's constructor. Thanks to #T.C. for pointing this out.
From ยง26.5.1.6/9 [rand.req.dist]
For each of the constructors of D taking arguments corresponding to parameters of the distribution, P shall have a corresponding constructor subject to the same requirements and taking arguments identical in number, type, and default values. ...
So we don't need to construct the distribution object needlessly only to extract the param_type. Instead the make_param_type function can be modified to
template <typename Distribution, typename... Args>
typename Distribution::param_type make_param_type(Args&&... args)
{
return typename Distribution::param_type(std::forward<Args>(args)...);
}
which can be used as
make_param_type<std::uniform_int_distribution<>>(0, 10)
Live demo
Answering my own question: by adapting an example found in this document, the following appears to be the correct way to implement a function returning a random integer between 0 and n-1 inclusive:
template<class URNG>
int rnd(int n, URNG &engine) {
using dist_t = std::uniform_int_distribution<>;
using param_t = dist_t::param_type;
static dist_t dist;
param_t params{0,n-1};
return dist(engine, params);
}
To make it thread-safe one must avoid the static declaration. One possibility is to make a convenience class along these lines, which is what I'm using in my own code:
template<class URNG>
class Random {
public:
Random(): engine(std::random_device{}()) {}
Random(typename std::result_of<URNG()>::type seed): engine(seed) {}
int integer(int n) {
std::uniform_int_distribution<>::param_type params {0, n-1};
return int_dist(engine, params);
}
private:
URNG engine;
std::uniform_int_distribution<> int_dist;
};
This is instantiated with (for example) Random<std::default_random_engine> rnd, and the random integers can then be obtained with rnd.integer(n). Methods for sampling from other distributions can easily be added to this class.
To repeat what I said in the comments, reusing the distribution object is probably unnecessary for the specific task of uniformly sampling integers, but for other distributions I think this will be more efficient than creating it every time, because there are some algorithms for sampling from some distributions that can save CPU cycles by generating multiple values simultaneously. (In principle even uniform_int_distribution could do this, via SIMD vectorisation.) If you can't increase efficiency by retaining the distribution object then it's hard to imagine why they would have designed the API this way.
Hooray for C++ and its needless complexity! This concludes an afternoon's work accomplishing a simple five-minute task, but at least I have a much better idea what I'm doing now.
The idiomatic way to generate code according to varying parameters is to create distribution objects as needed, per Vary range of uniform_int_distribution:
std::random_device rd;
std::default_random_engine eng{rd()};
int n = std::uniform_int_distribution<>{0, A}(eng);
If you are concerned that performance may be hindered by failing to fully exploit the distribution's internal state, you can use a single distribution and pass it different parameters each time:
std::random_device rd;
std::default_random_engine eng{rd()};
std::uniform_int_distribution<> dist;
int n = dist(eng, decltype(dist)::param_type{0, A});
If this seems complicated, consider that for most purposes you will generate random numbers according to the same distribution with the same parameters (hence the distribution constructor taking parameters); by varying parameters you are already entering into advanced territory.
I am trying to create a jump table for a fuzzy controller. Basically, I have a lot of functions that take in a string and return a float, and I want to be able to do something along the lines:
float Defuzzify(std::string varName, DefuzzificationMethod defuzz)
{
return functions[defuzz](varName);
}
where DefuzzificationMethod is an enum. The objective is to avoid a switch statement and have a O(1) operation.
What I have right now is:
float CenterOfGravity(std::string varName);
std::vector<std::function<float (std::string)>> defuzzifiers;
Then I try to initialize it in the constructor with:
defuzzifiers.reserve(NUMBER_OF_DEFUZZIFICATION_METHODS);
defuzzifiers[DEFUZZ_COG] = std::bind(&CenterOfGravity, std::placeholders::_1);
This is making the compiler throw about 100 errors about enable_if (which I don't use anywhere, so I assume std does). Is there a way to make this compile ? Moreover, is there a way to make this a static vector, since every fuzzy controller will essentially have the same vector ?
Thanks in advance
Reserve just makes sure there's enough capacity, it doesn't actually mak the vector's size big enough. What you want to do is:
// construct a vector of the correct size
std::vector<std::function<float (std::string)>> defuzzifiers(NUMBER_OF_DEFUZZIFICATION_METHODS);
// now assign into it...
// if CentorOfGravity is a free function, just simple = works
defuzzifiers[DEFUZZ_COG] = CenterOfGravity;
// if it's a method
defuzzifiers[DEFUZZ_COG] = std::bind(&ThisType::CenterOfGravity, this, std::placeholders::_1);
Now this might leave you some holes which don't actually have a function defined, so maybe you want to provide a default function of sorts, which the vector constructor allows too
std::vector<std::function<float (std::string)>> defuzzifiers(
NUMBER_OF_DEFUZZIFICATION_METHODS,
[](std::string x) { return 0f; }
);
An unrelated note, you probably want your functions to take strings by const-ref and not by value, as copying strings is expensive.
I am using a uniform_int_distribution in Boost 1.52 to generate random numbers using the basic boilerplate code:
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
boost::random::mt19937 gen;
int roll_die()
{
boost::random::uniform_int_distribution<> dist(1, 6);
return dist(gen);
}
int main()
{
for (int i = 0; i < 10; i++) std::cout << roll_die() << std::endl;
}
I implemented parts of this in a much larger project and it works great. Here is my question.
In the above function, it seems like the dist object is local to the function. If you call roll_die() many many times, it seems like having dist() be local to the function would introduce a lot of overhead.
I'm thinking it would be better to set the min and max parameters of this object once, and then only have one instance of dist in a bigger object or something. How does one do this? I tried to understand the "Public Member Functions" portion of the class template: http://www.boost.org/doc/libs/1_47_0/doc/html/boost/random/uniform_int_distribution.html#id744736-bb but it was over my head. In that documentation I see:
void param(const param_type & param); //Sets the parameters of the distribution.
How do you actually use this? Is .param() itself a function to call, or is it a stand-in for another function? I couldn't find another boost example that did what I'm asking. Thanks in advance for your assistance and advice!
it seems like ... would introduce a lot of overhead.
You may assume it does, but do you actually know this? You should not make any assumptions if anything is faster or slower without actually running a profiler or benchmarking the code in some other way. If you look at the source, you can see that uniform_int_distribution's constructor merely assigns the min and max values - which should be really insignificant overhead. Especially if you take into account that the actual random number generation will be a much more complex operation than two assignments. So I'd suggest you leave the code as is, and if your program is too slow, you can always profile and then optimize.
Edit: To quote Djikstra: "Premature optimization is the root of all evil". Way too often, programmer's write more complex code than need be, simply because they think it will be faster. Don't do it - only start optimizing when there are speed problems.
Anyway, to answer your questions: param() is a member of uniform_int_distribution. It takes an object of type uniform_int_distribution::param_type. You can use it like so:
using namespace boost::random;
// Create an uniform_int_distribution object
uniform_int_distribution<> dist(1, 6);
// Create a params object
uniform_int_distribution::param_type newParams(10, 500);
// The following will reconfigure dist to have 10 and 500 as
// min and max value
dist.param(newParams);
This way, you can reconfigure a single distribution object as often as you like. But the "overhead" will likely be the same as constructing a new distribution object.
Another way you can ensure that the object is only created once:
int roll_die()
{
static boost::random::uniform_int_distribution<> dist(1, 6);
return dist(gen);
}
Declaring variables inside of functions as static has a similar effect as if the variable where global, but it's only visible in the function's scope.
I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:
using namespace boost::accumulators;
//stuff...
accumulator_set<vector<double>, stats<tag::mean> > acc;
vector<double> some_vetor;
//stuff
some_vector = doStuff();
acc(some_vector);
maybe this is obvious, but I tried anyway. :P
What I wanted was to have an accumulator that would calculate a vector which is the mean of the components of many vectors. Is there an easy way out?
EDIT:
I don't know if I was thoroughly clear. I don't want this:
for_each(vec.begin(), vec.end(),acc);
This would calculate the mean of the entries of a given vector. What I need is different. I have a function that will spit vectors:
vector<double> doSomething();
// this is a monte carlo simulation;
And I need to run this many times and calculate the vectorial mean of those vectors:
for(int i = 0; i < numberOfMCSteps; i++){
vec = doSomething();
acc(vec);
}
cout << mean(acc);
And I want mean(acc) to be a vector itself, whose entry [i] would be the means of the entries [i] of the accumulated vectors.
Theres a hint about this in the docs of Boost, but nothing explicit. And I'm a bit dumb. :P
I've looked into your question a bit, and it seems to me that Boost.Accumulators already provides support for std::vector. Here is what I could find in a section of the user's guide :
Another example where the Numeric
Operators Sub-Library is useful is
when a type does not define the
operator overloads required to use it
for some statistical calculations.
For instance, std::vector<> does not overload any arithmetic operators, yet
it may be useful to use std::vector<>
as a sample or variate type. The
Numeric Operators Sub-Library defines
the necessary operator overloads in
the boost::numeric::operators
namespace, which is brought into scope
by the Accumulators Framework with a
using directive.
Indeed, after verification, the file boost/accumulators/numeric/functional/vector.hpp does contain the necessary operators for the 'naive' solution to work.
I believe you should try :
Including either
boost/accumulators/numeric/functional/vector.hpp before any other accumulators header
boost/accumulators/numeric/functional.hpp while defining BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
Bringing the operators into scope with a using namespace boost::numeric::operators;.
There's only one last detail left : execution will break at runtime because the initial accumulated value is default-constructed, and an assertion will occur when trying to add a vector of size n to an empty vector. For this, it seems you should initialize the accumulator with (where n is the number of elements in your vector) :
accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(n));
I tried the following code, mean gives me a std::vector of size 2 :
int main()
{
accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(2));
const std::vector<double> v1 = boost::assign::list_of(1.)(2.);
const std::vector<double> v2 = boost::assign::list_of(2.)(3.);
const std::vector<double> v3 = boost::assign::list_of(3.)(4.);
acc(v1);
acc(v2);
acc(v3);
const std::vector<double> &meanVector = mean(acc);
}
I believe this is what you wanted ?
I don't have it set up to try right now, but if all boost::accumulators need is properly defined mathematical operators, then you might be able to get away with a different vector type: http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/vector.htm
And what about the documentation?
// The data for which we wish to calculate statistical properties:
std::vector< double > data( /* stuff */ );
// The accumulator set which will calculate the properties for us:
accumulator_set< double, features< tag::min, tag::mean > > acc;
// Use std::for_each to accumulate the statistical properties:
acc = std::for_each( data.begin(), data.end(), acc );