Solved

Posted on 2004-11-30

hi,

function rand() in C++ generates a random variable which is uniformly distributed but i want to generate a random variable that is exponentialy distributed or normally distributed. can any one tell me the code for doing this.

Saira

function rand() in C++ generates a random variable which is uniformly distributed but i want to generate a random variable that is exponentialy distributed or normally distributed. can any one tell me the code for doing this.

Saira

8 Comments

#include <time.h>

int main( void )

{

int i;

/* Seed the random-number generator with current time so that

* the numbers will be different every time we run.

*/

srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */

for( i = 0; i < 10;i++ )

printf( " %6d\n", rand() );

return 0;

}

This should be done in the main() when the program first starts up.

the original question was not about same rand() values all the time (as usually is) but about the distribution.

The answer is NO. You may find some algorithms on internet, but you have to implement other distributions by yourself. If I want to use some approximation to normal distribution I usually make mean of several uniformly distributed values:

randVal = (rand () + rand () + rand () + rand ()) / 4 ;

This is enough for me (though it is 4x slower than just rand()). If you need more precise solution I'll try to find something else.

S.

saira

randVal -= RAND_MAX / 2 ; // this makes mean 0

randVal *= X ; // this sets the variance to X

-----

anyway. have you tried simple rewriting of mathematical formulas (http://astronomy.swin.edu

normal distribution:

x = rand () ;

m = mean ;

s = variance ;

pi = 3.1415 ;

y = 1 / (s * sqrt (2*pi)) * exp (-0.5 * pow ((x-m)/s, 2)) ;

exponential:

x = rand () ;

l = lambda ;

y = (x>=0 && l>0)? l * exp (-l * x) : 0 ;

S.

double value = my_gaussian_function(rand(

The fun part is implementing those functions. If it were me implementing it, I would use a lookup table of about 256 elements, and do a second-order polynomial extrapolation taking the nearest four values. Good luck!

Title | # Comments | Views | Activity |
---|---|---|---|

C++ assignment question | 7 | 115 | |

How to convert utf32 to utf16 using C++ on Ubuntu Linux 15.10 with the gcc c++11 compiler. | 4 | 115 | |

C++ to C# code conversion issue | 4 | 73 | |

Socket Programming (Unix) | 8 | 74 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**24** Experts available now in Live!