# RandF function. (Rand Float)

This is a discussion on RandF function. (Rand Float) within the C++ Programming forums, part of the General Programming Boards category; I've made a small random float function. You could use it if you need, could be useful for 3d. Here ...

1. ## RandF function. (Rand Float)

I've made a small random float function.

You could use it if you need, could be useful for 3d.

Here it is.

Code:
```#include <iostream>
#include <windows.h>
#include <string>
#include <time.h>

using namespace std;

float randf(float num)
{

int r = rand()%1;

float FinalRandValue = 0.0f;

char numstr[32];

string NumValue[2];
int at = 0;

sprintf_s(numstr, 32, "%f", num);

do
{
NumValue[0] += numstr[at];
at++;
}while(numstr[at] != '.');

for(size_t i = at+1; i < strlen(numstr)-3; i++)
{
NumValue[1] += numstr[i];
}

int Number1 = atoi(NumValue[0].c_str());
int Number2 = atoi(NumValue[1].c_str());
Number2 += 1;
Number2 /= 10;

int Random1 = 0;
int Random2 = 0;

if(Number1 > 0)
{
Random1 = rand()%Number1;
}
if(Number2 > 0)
{
Random2 = rand()%Number2;
}

ZeroMemory(&numstr, sizeof(numstr));

if(Random2 < 10)
{
sprintf_s(numstr, 32, "%d.0%d", Random1, Random2);
}
else
{
sprintf_s(numstr, 32, "%d.%d", Random1, Random2);
}

FinalRandValue = (float)atof(numstr);

return FinalRandValue;

}

int main()
{

srand(time_t(0));

while(1)
{
randf(1000.99f);
Sleep(500);
}

return 0;

}```
Have fun.

2. Not to ruin your day, but for what it's worth . . .
Code:
```#include <stdlib.h>

double randf(double max = 1.0);

double randf(double max) {
return (std::rand() / static_cast<double>(RAND_MAX)) * max;
}```

3. haha, it's ok , only wasted 10 minutes.

4. I know you didn't ask for comments, but I want to know: why in the world are we using char arrays and C++ strings here? (I could also ask why we're doing %1, which does nothing except use up a call to rand.)

5. time_t(0)

is more secure but, it will rand the first value to the same number everytime.

I could've used it only once before using randf() but i just decided to put it into the function.

6. You are calling srand(), right? That should give you a sequence of numbers that is different. The first call to rand() will be different along with everything else.

Of course, how different depends on the seed you pass to srand(). If you use time() to seed srand(), for example, then you'll get the same sequence of numbers if you run the program twice within one second.

Also, instead of using the Windows-specific ZeroMemory, you can use the standard C function memset() to do much the same thing.

7. Code:
```float GetRandomFloatInRange(float min,float max)
{
unsigned int value = rand % 1000;
float coef = static_cast<float>(value) / 1000.0f;

return min + coef * (max - min);
}```
Replace the call to rand() with a call to a better pseudo-random number generator and it's even more useful.

8. O_o

Why aren't you using RAND_MAX (or whatever it is)?

Code:
`srand(time_t(0));`
Anyway, that is probably the same as seeding with zero which explain why you are getting the same first number ever time.

Soma

9. You can also make it into a class, allowing it to be used a generator, as well (just keep in mind that I just put this together so it may have some bugs in it):

Code:
```#include <ctime>
#include <cstdlib>

class random_generator
{
public:

random_generator( void )
: value_( 0.0 ), low_( 0.0 ), high_( 1.0 )
{	}

random_generator( double low, double high )
: value_( 0.0 ), low_( low ), high_( high )
{	}

random_generator& operator ( )( double low, double high )
{
low_ = low;
high_ = high;
return ( *this )( );
}

random_generator& operator ( )( void )
{
value_ = low_ +
(
( high_ - low_ ) * ( std::rand( ) % RAND_MAX )
) / double( RAND_MAX );
return *this;
}

inline operator double( void ) const
{
return value_;
}

inline double value( void ) const
{
return value_;
}

inline double low( void ) const
{
return low_;
}

inline double high( void ) const
{
return high_;
}

static void seed( int initial = 0 )
{
std::srand( initial ? initial : std::time( 0 ) );
}

protected:

double
value_,
low_,
high_;

struct seed_initializer
{
seed_initializer( void )
{
seed( );
}
};

static seed_initializer const
initialize;
};

random_generator::seed_initializer const
random_generator::initialize = random_generator::seed_initializer( );```
Example:

Code:
```#include <vector>
#include <iostream>
#include <iterator>

using namespace std;

int main( void )
{
vector< double >
data( 13 );
generate( data.begin( ), data.end( ), random_generator( -3114, 2012 ) );
copy( data.begin( ), data.end( ), ostream_iterator< double, char >( cout, "\n" ) );
return 0;
}```

10. Hehe, reviving an old thread.

As i come back, and check out my randf code, i recognize that all the codes you've shown me doesn't work.

That's cause the way you did it doesn't work.

Try out your codes again, and see if it rands a float value or double.

lol...you'll see the things you did are wrong .

As i come back, and check out my randf code, i recognize that all the codes you've shown me doesn't work.

That's cause the way you did it doesn't work.

Try out your codes again, and see if it rands a float value or double.

lol...you'll see the things you did are wrong
dwks' example is not quite correct since the example header inclusion was <stdlib.h>, but std::rand is available via <cstdlib>, yet this mistake is easily corrected. It also generates a double in the range [0.0, max] rather than the more usual [0.0, max), but that certainly is not a case of "doesn't work".

So, with this counterexample I put it to you that your claim is exaggerated: more likely it is you who have not taken simple steps to correct any trivial errors, or you simply have failed to use the suggestions correctly, e.g., by recognising that with phantomotap's observation you should change srand(time_t(0)) to say, srand(time(0)). (But read Prelude's article on Using rand().)

As i come back, and check out my randf code, i recognize that all the codes you've shown me doesn't work.

That's cause the way you did it doesn't work.

Try out your codes again, and see if it rands a float value or double.

lol...you'll see the things you did are wrong .
That's an absolutely outrageous and false claim!

What values do you expect to get back from randf(1.5f)? The rest of us all expect several evenly distributed values between 0 and 1.5 with equal probabilities of each outcome. Your function has two possible outputs in such a case:
• 0
• 1
Doesn't look very useful to me!
It also will probably crash if the number given is a whole number.
It fails if the parameter given is too small or too large, e.g. 1.0E-33.
It is very slow.
It calls rand() THREE times, unnecessarily shortening the period of the prng.
I'm pretty sure that the +1 and divide by 10 introduce other bugs.
'r' isn't even used.
What, no unit tests?

Anyone who has any clue what they are doing will write something like what Bubba wrote, and it will work exactly as it should.

13. Originally Posted by iMalc
Anyone who has any clue what they are doing will write something like what Bubba wrote, and it will work exactly as it should.
Speaking of which it is also technically true that Bubba's example "doesn't work", but once again it is a trivial error (rand should be rand()), not a problem with the underlying method that was demonstrated. That said, the use of modulo 1000 seems a little unnecessary: I would expect something like this instead:
Code:
```float GetRandomFloatInRange(float min, float max)
{
return min + (rand() / (RAND_MAX + 1.0f)) * (max - min);
}```