简体   繁体   中英

What is the best way to implement a pseudo-random number generator in C++ that supports querying the nth random number for a given seed?

My use case is that I am doing something akin to generative art that involves lazy range-v3 range views containing randomly generated geometric primitives.

I am limited by the fact that for certain operations, when iterating over the aggregate range view, the computation performed by the range views' iteration implementation requires accessing the same random number twice. These numbers are ultimately coming from ranges::views::generate returning numbers generated by std::mt19937 . When the generate happens twice it will return different numbers.

One way around this problem would be to do basically the following instead of using views::generate :

ranges::views::iota(0) | 
ranges::views::transform([](int n){return nth_random_number(n, some_rnd_engine);}

my question is is it possible to implement nth_random_number(i, some_rnd_engine) on top of anything in the standard library, or otherwise. Note that the above is just pseudocode in the actual code I need the separation between engine and distribution, etc., as in the standard library.

I've read that a linear congruential engine should be able to do this, and indeed there is one in the standard library , but I believe there is no standard way to access its internal state in a rich enough way to implement the feature I want.

Yes, its possible, but it will be horribly slow.
It would involve resetting the generator back to the start with the same seed (probably by recreating it over each time) then calling discard to advance the generator by n. https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine/discard

You could also do it for a generator that doesn't have discard by simply calling the generator N times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM