I am trying to pick a random point on a unit sphere, and found that boost provides the distribution that does exactly this. But when I try to use it, all generated values are nan. I don’t know what I am doing wrong, could you please enlighten me? This small code depicts what I am trying to do:
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_on_sphere.hpp>
int main()
{
boost::mt19937 gen;
boost::uniform_on_sphere<float> dist(3);
{ // Seed from system random device
std::ifstream rand_device("/dev/urandom");
uint32_t seed;
rand_device >> seed;
gen.seed(seed);
}
while(1) {
// Generate a point on a unit sphere
std::vector<float> res = dist(gen);
// Print the coordinates
for(int i = 0; i < res.size(); ++i) {
std::cout << res[i] << ' ';
}
std::cout << '\n';
}
}
The output is:
nan nan nan
nan nan nan
nan nan nan
nan nan nan
ad infinitum…
I’m assuming you are using Boost 1.49. The method below works in that case.
This is where Boost is a little complicated. The object that is
uniform_on_sphereis just one component of what you need in order to draw points, it is the distribution part.. You also need to create aboost::variate_generatoralong the lines of the following working .cpp file below.Note, this has my own includes for using the system time to seed, etc. You should be able to modify this to suit you.
When I run this in the console, I get seemingly correct stuff: