R.Mckemey - 3 months ago 10

C++ Question

I want to take a random string of 32 bits and declare this bit string to be a float in

`C++`

For example the string

`0.0111 1111.1000 0000 0000 0000 0000 000`

`1.5`

`.5`

If a string is not a good data format for this then I'd be happy to hear suggestions.

In fact I want to create a random floating point number in C++ but I don't know how. Where by random I mean each bit is independently 0 or 1. The solutions (for example here: C++ random float number generation) I've found suggest using a random integer generator then dividing by the

`RAND_MAX`

`FLOAT_MAX`

Basically this question but for C++: Convert Double to Binary representation?

Answer

If you just want a RNG that spits out a exponentially distributed floats, you don't have to worry about binary representation. Just use math.

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <math.h>
int main (void) {
int i;
srand (time(NULL));
// Make 10 'random' floats
for (i = 0; i < 10; ++i)
{
// Float exponents go from -128 to 127
float exponent = -128 + 256 * (float) rand() / RAND_MAX;
float result = pow(2, exponent);
printf ("%g\n", result);
}
return 0;
}
```

If you want to arbitrarily generate bytes interpreted as float, you can do this instead...

```
int i = rand();
float result = *((float *)&i);
printf ("%g\n", result);
```