CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

Random Number Generator Help

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Megadave



Joined: 04 Jan 2011
Posts: 4

View user's profile Send private message

Random Number Generator Help
PostPosted: Tue Jan 25, 2011 12:03 pm     Reply with quote

Hello

I am using a random number generator that allows me to generate a number within a specific range. The routine works great but I need to use it on a 16f688. Unfortunately the routine uses a lot of ROM not leaving enough room for the other functions. I have identified the section that is causing the high ROM usage which is the division of a float number. Without the (float) the random number generator does not work. Does anyone know of a better way of doing this or better yet doing float point math without using float?

Thanks

Code:


#define  READ_SEED                read_eeprom32(2)
#define  SAVE_SEED(x)            write_eeprom32(2,x)

int16 random(int min,int max)
{
   int16 rand;                                                                  // Declare a temporary 16-bit variable
   max = (max + 1);                                                             // Increment max so that max value is used otherwise max-1 is performed
   seed = READ_SEED;                                                            // Get last known seed value from NV memory
   seed = seed * 1103515245 + 12345;                                            // Calculate new seed value
   SAVE_SEED(seed);                                                             // Save seed value in NV memory
   rand =(int16) (seed >> 16) % 32767;                                          // Generate a random number
   return((int16)min + rand *((max - min)/(float)32767));                         // Return random number between specified range                   
}

[/quote]
Megadave



Joined: 04 Jan 2011
Posts: 4

View user's profile Send private message

PostPosted: Tue Jan 25, 2011 12:10 pm     Reply with quote

I figured it out! If I do this it works!

Code:

return ((int16)rand%(max-min+1)+min);
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group