# 11.12 Getting a Random Floating-Point Value with Uniform Distribution

#### 11.12.1 Problem

When looking for a random floating-point number, we usually want a value between 0 and 1 that is just as likely to be between 0 and 0.1 as it is to be between 0.9 and 1.

#### 11.12.2 Solution

Because of the way that floating-point numbers are stored, simply casting bits to a float will make the distribution nonuniform. Instead, get a random unsigned integer, and divide.

#### 11.12.3 Discussion

Because integer values are uniformly distributed, you can get a random integer and divide so that it is a value between 0 and 1:

```#include <limits.h>

double spc_rand_real(void) {
return ((double)spc_rand_uint(  )) / (double)UINT_MAX;
}```

Note that to get a random number between 0 and n, you can multiply the result of spc_rand_real( ) by n. To get a real number within a range inclusive of the range's bounds, do this:

```#include <stdlib.h>

double spc_rand_real_range(double min, double max) {
if (max < min) abort(  );
return spc_rand_real(  ) * (max - min) + min;
}```

 Foreword
 Preface
 Chapter 1. Safe Initialization
 Chapter 2. Access Control
 Chapter 3. Input Validation
 Chapter 4. Symmetric Cryptography Fundamentals
 Chapter 5. Symmetric Encryption
 Chapter 6. Hashes and Message Authentication
 Chapter 7. Public Key Cryptography
 Chapter 8. Authentication and Key Exchange
 Chapter 9. Networking
 Chapter 10. Public Key Infrastructure
 Chapter 12. Anti-Tampering
 Chapter 13. Other Topics
 Colophon