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. #1
    kevinawad
    Guest

    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.
    Last edited by kevinawad; 06-16-2009 at 02:21 PM.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,041
    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;
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

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

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    13,007
    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. #5
    kevinawad
    Guest
    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. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,041
    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.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,515
    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.
    Arrogance breeds bad code

  8. #8
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    3,005
    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. #9
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Posts
    5,439
    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;	
    }
    Last edited by Sebastiani; 06-16-2009 at 06:48 PM.
    Code:
    int main(void){srand(time(0));for(double l=rand(),l0=0,l00=0;;l0+=0.1){for(double l000=0;l000
    <1;l000+=.001,l+=((double)rand()/RAND_MAX)/0x64,l00+=((sin(l*0x8*atan(l0)*l000-(l0*0x8*atan
    (l)))*0.5)+0.5)){l00-=floor(l00);for(size_t l0000=0,l00000=(size_t)(0x50*(l00));l0000<l00000;++l0000
    )putchar(0x20);putchar(0x61+(int)((double)rand()/RAND_MAX*0x1a));putchar('\n');}}return 0;}

  10. #10
    kevinawad
    Guest
    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 .

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    19,384
    Quote Originally Posted by kevinawad
    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().)
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,028
    Quote Originally Posted by kevinawad View Post
    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 .
    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.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    19,384
    Quote 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);
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21