dimanche 7 juin 2015

Random Float Generator

I'm learning c++ and I'm trying to generate a random float and seem to be having some difficulties.

I start by making a random int(), newRandom, between -100 and 100, then I take that newRandom and turn it into a random float, rand_X, between -1.0 and 1.0. The only caveat is I don't want rand_X to be between -0.2 and 0.2, in other words,

-1.0 <= rand_X <= -0.2 and 0.2 <= rand_X <= 1.0.

Here's my code,

#include "stdafx.h"
#include <iostream>
#include <random>

int newRandom() {
    int newRandom = 0;
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(-100, 100); // define the range

    newRandom = distr(eng);

    return newRandom;
}

float newRandomX() {
    float rand_X = newRandom() / 100.0f;
    for (int n = 0; n > 0; n++) {
        if (rand_X < 0.0f && rand_X > -0.2f) {
            rand_X = newRandom() / 100.0f;
        }
        else if (rand_X > 0.0f && rand_X < 0.2f) {
            rand_X = newRandom() / 100.0f;
        }
        else {
            return rand_X;
        }
    }
}

int main()
{
    float dir_x = newRandomX();
    std::cout << dir_x;
}

I usually set a break point at the closing bracket of main() and this is my output in the console window, -nan(ind)

As I said I'm learning the language so I'm probably doing something very silly. Thanks very much for your help!




Aucun commentaire:

Enregistrer un commentaire