Generating random double/float typed numbers

Nov 22, 2011 at 10:09am
closed account (42hU7k9E)
How can this be done? Can somebody please explain it to me?
Nov 22, 2011 at 11:17am
One way to do so can be to generate 2 numbers (using rand()).
Divide one of them by a multiple of 10. Add the result to the original number.
e.g.
First number: 25
Second Number: 35.
Divide second by 100 (102) and add it to the original.

25 + 0.35 = 25.35
Nov 22, 2011 at 12:58pm
another possibillity is to do a linear mapping of rand(). (obvious problem, resolution)
You could also play with the bits. Wonder what distribution will that give you.
Nov 22, 2011 at 12:59pm
Depending how random you want your random number to be, you could try getting a random integer of the same size and reinterpret_cast it to a double/float. Is there a specific range you want to limit the random number to?
Nov 22, 2011 at 5:49pm
Modern standard C++ has uniform_real_distribution which provides floating-point random numbers. It was introduced in the TR1 library extension in 2005 and became part of the C++ standard in 2011.

Example (works in Visual Studio 2010, gcc 4.5.2, and most other modern compilers)

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <random>
using namespace std;
int main() {
    random_device rd; // access hardware RNG
    default_random_engine e(rd()); // seed the software PRNG
    uniform_real_distribution<> d(-1, 1); // range
    for(int n = 0; n<100; ++n)
        cout << d(e) << ' ';
    cout << '\n';
}


demo: http://ideone.com/fUdYC

For legacy compilers, uniform_real_distribution is available as part of the library boost.random: http://www.boost.org/doc/libs/release/doc/html/boost_random.html
Topic archived. No new replies allowed.