-3

The title pretty much says it all. I've looked online but I couldn't find anything for this language. I've seen the following: ((double) rand() / (RAND_MAX)) with no luck. I'd also like to avoid using external library's.

The value should be a float as I'm working out X,Y coordinates.

Jake
  • 1
  • 1
  • 1

3 Answers3

2

If you are using C++11, you can use the random header for this. You will need to create a generator, then define a distribution over this generator, and then you can use the generator and the distribution to get your results. You need to include random

#include <random>

Then define the generator and your distribution

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(-1,1); //doubles from -1 to 1

Then you can get random numbers like so

double random_number = distribution(generator);

If you need more information it is available here http://www.cplusplus.com/reference/random/

JHobern
  • 866
  • 1
  • 13
  • 20
1

Maybe ((double) rand() / (RAND_MAX)) * 2 - 1.

i486
  • 6,491
  • 4
  • 24
  • 41
-2

Don't simply use rand() because it's not random, just pseudo random!

unsigned int rand_interval(unsigned int min, unsigned int max)
{
    int r;
    const unsigned int range = 1 + max - min;
    const unsigned int buckets = RAND_MAX / range;
    const unsigned int limit = buckets * range;

    /* Create equal size buckets all in a row, then fire randomly towards
     * the buckets until you land in one of them. All buckets are equally
     * likely. If you land off the end of the line of buckets, try again. */
    do
    {
        r = rand();
    } while (r >= limit);

    return min + (r / buckets);
}

This is a fully functioning code. (Don't forget to seed rand with srand() in main!

Note> I can't take credit for it as I have also seen it somewhere online and I'm using it myself for some time.

Rorschach
  • 734
  • 2
  • 7
  • 22
  • 2
    How on earth is this _not_ pseudorandom? I don't see a hardware device here. – Useless Oct 28 '15 at 11:22
  • Correct. I misspoke. Wanted to say its _more_ random than simply doing `number = rand()`, or something similar. – Rorschach Oct 28 '15 at 11:25
  • @user3735245 just an advice: never mess with probabilities and/or randomness unless you are PhD in mathematics. – Galimov Albert Oct 28 '15 at 11:27
  • 2
    Yeah, you _think_ it's more random, it looks like it _could/should/might_ be more random, but unless you've spent a lot of effort looking for patterns and/or thinking very hard, you're probably just wrong. Random number generation is notorious for Dunning-Krugering the unwary. – Useless Oct 28 '15 at 11:32