1

Possible Duplicate:
C++ | Generating a truly random number between 10-20
How to generate random number within range (-x,x)

So I am using a MT to generate my pseudo random numbers, I want to be able to modify these numbers into a value in a range of numbers.

These are the functions I have right now, the first two are int's and the second two are float's, but they do not seem to work right.

static inline int randomi(int min, int max)
{
    return Random() % (max-min)+min;
}

static inline unsigned long randomi(int max)
{
    return Random() % max;
}

static inline float randomf(float min, float max)
{
    return (Random() / ULONG_MAX) * (max-min)+min;
}

static inline float randomf(float max)
{
    return (Random() / ULONG_MAX) * max;
}

How can I make these work so they can return ranges that are can be anywhere between including negative ranges or ranges that are on either side of the 0;

Community
  • 1
  • 1
Baraphor
  • 249
  • 4
  • 16
  • Assuming `Random()` returns an `unsigned long`, the operation `Random() / ULONG_MAX` results in an `unsigned long` either 0 or 1 (1 being extremely unlikely). Instead, use `Random() / (float) ULONG_MAX`. – larsmoa Nov 03 '12 at 16:14

1 Answers1

2

When you need a negative number as a limit, just shift the whole selection down...

ex:

* you need a random between -10 and +10:
* generate a random from 0 to 20 the do -10.

For you to implement..

Frank
  • 16,476
  • 7
  • 38
  • 51