点云---随机数生成之数据采样

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <vector>

float unifRand()
{
    return (static_cast<float>(rand() / double(RAND_MAX)));
    //return (((214013 * seed_ + 2531011) >> 16) & 0x7FFF);
}

int randomSample(std::vector<int>&indices_, unsigned int& N, const unsigned int& sample_size, std::vector<int>&indices) {

    //unsigned N = static_cast<unsigned> (30);   //max
    //unsigned int sample_size = 20;

    //std::vector<int>indices;
    //std::vector<int>indices_(N);

    for (size_t i = 0; i < N; i++)
    {
        indices_[i] = i;
    }
    // If sample size is 0 or if the sample size is greater then input cloud size
    //   then return all indices
    if (sample_size >= N)
    {
        printf("sample_size >= N ......");//
    }
    else
    {
        // Resize output indices to sample size
        indices.resize(static_cast<size_t> (sample_size));

        // Set random seed so derived indices are the same each time the filter runs
        std::srand(static_cast<unsigned int>(time(NULL)));

        // Algorithm A
        unsigned top = N - sample_size;
        unsigned i = 0;
        unsigned index = 0;

        for (size_t n = sample_size; n >= 2; n--)
        {
            float V = unifRand();
            unsigned S = 0;
            float quot = static_cast<float> (top) / static_cast<float> (N);
            while (quot > V)
            {
                S++;
                top--;
                N--;
                quot = quot * static_cast<float> (top) / static_cast<float> (N);
            }
            index += S;
            indices[i++] = indices_[index++];
            N--;
        }
    }

    return 0;
}

int main(int argc, char** argv)
{

    /*****************方法一****************/
    //方法一 会产生重复数字
    /*
    int n = 30;
    double U;
    int random_num;

    srand(static_cast<unsigned int>(time(NULL)));  //初始化随机数种子
    for (int i = 0; i < 20; i++)
    {
        U = (double)rand() / RAND_MAX; //生成[0,1]之间的随机数
        random_num = (int)((n - 1)*U + 0.5); //生成[0,n-1]之间的随机数
        printf("%d ", random_num);
    }*/

    /*****************方法二****************/
    unsigned int N = static_cast<unsigned int> (30);   //max
    unsigned int sample_size = 20;
    std::vector<int>indices;
    std::vector<int>indices_(N);
    randomSample(indices_, N, sample_size, indices);

    return 0;
}

 

        inline int randomGeneration(const int& max_num, const int gen_num, std::vector<int>& random_num_vec) {
            for (int i = 0; i < abs(gen_num); i++)
            {
                double U = (double)rand() / RAND_MAX; //生成[0,1]之间的随机数
                int random_num = (int)((max_num - 1)*U + 0.5); //生成[0,max_num-1]之间的随机数
                random_num_vec.push_back(random_num);
            }
            return 0;
        };

 

posted @ 2020-02-28 18:07  玥茹苟  阅读(703)  评论(0编辑  收藏  举报