作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在单位球体上选择一个随机点,发现 boost 提供的分布正是这样做的。但是当我尝试使用它时,所有生成的值都是 nan
。我不知道我做错了什么,你能赐教吗?这段小代码描述了我正在尝试做的事情:
#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';
}
}
输出是:
nan nan nan
nan nan nan
nan nan nan
nan nan nan
无限...
最佳答案
我假设您使用的是 Boost 1.49。以下方法适用于这种情况。
这是 Boost 有点复杂的地方。 uniform_on_sphere
对象只是绘制点所需的组件之一,它是分布部分。您还需要创建一个 boost::variate_generator
按照下面的以下工作 .cpp 文件。
请注意,这有我自己的包括使用系统时间播种等。您应该能够修改它以适合您。
// Standards, w/ctime to seed based on system time.
#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
// Boost. Requires variate_generator to actually draw the values.
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_on_sphere.hpp>
#include <boost/random/variate_generator.hpp>
int main(){
typedef boost::random::mt19937 gen_type;
// You can seed this your way as well, but this is my quick and dirty way.
gen_type rand_gen;
rand_gen.seed(static_cast<unsigned int>(std::time(0)));
// Create the distribution object.
boost::uniform_on_sphere<float> unif_sphere(3);
// This is what will actually supply drawn values.
boost::variate_generator<gen_type&, boost::uniform_on_sphere<float> > random_on_sphere(rand_gen, unif_sphere);
// Now you can draw a vector of drawn coordinates as such:
std::vector<float> random_sphere_point = random_on_sphere();
// Print out the drawn sphere triple's values.
for(int i = 0; i < random_sphere_point.size(); ++i) {
std::cout << random_sphere_point.at(i) << ' ';
}
std::cout << '\n';
return 0;
}
当我在控制台中运行它时,我得到了看似正确的东西:
ely@AMDESK:~/Desktop/Programming/C++/RandOnSphere$ g++ -I /usr/include/boost_1_49/ -L /usr/include/boost_1_49/stage/lib randomOnSphere.cpp -o ros
ely@AMDESK:~/Desktop/Programming/C++/RandOnSphere$ ./ros
0.876326 -0.0441729 0.479689
ely@AMDESK:~/Desktop/Programming/C++/RandOnSphere$ ./ros
-0.039037 -0.17792 0.98327
ely@AMDESK:~/Desktop/Programming/C++/RandOnSphere$ ./ros
-0.896734 0.419589 -0.14076
关于c++ - 如何使用 boost::uniform_on_sphere?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202420/
我试图在单位球体上选择一个随机点,发现 boost 提供的分布正是这样做的。但是当我尝试使用它时,所有生成的值都是 nan。我不知道我做错了什么,你能赐教吗?这段小代码描述了我正在尝试做的事情: #i
问题 在正确生成二维随机向量一段时间后,boost::uniform_on_sphere 分布突然生成一个值为 -nan 的向量。我已经在三台机器上测试了包含的程序 - 在其中两台机器上观察到错误,但
我是一名优秀的程序员,十分优秀!