#07 (02/07/2024)

Random numbers ( Monte Carlo simulations)

A program to print random numbers 10 times.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;

for (i=0; i <  10; i++)  printf("%d\n", rand());

printf("\nMAX = %d\n", RAND_MAX);

return 0;
}

rand() returns an integer between 0 and RAND_MAX defined in stdlib.h.
Generate random numbers between 0 and 1.0.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
for (i=0; i< 10; i++)  printf("%f\n", 1.0*rand()/RAND_MAX);
printf("\nMAX = %d\n", RAND_MAX);
return 0;
}

srand() sets its argument as the seed for a new sequence of pseudo-random integers.
If no seed value is provided, the rand() function is automatically seeded with a value of 1.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
printf("Enter seed integer = ");
scanf("%d", &i);
srand(i);

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

return 0;
}

time() defined in <time.h> with the argument NULL returns the elapsed time since 00:00:00 GMT, January 1, 1970, measured in seconds.

#include <stdio.h>
#include <time.h>

int main()
{
int i;

printf("%d\n", time(NULL));
return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{

srand(time(NULL));
printf("%d\n", rand());
return 0;
}

Generating random numbers in arbitrary range

  1. rand() returns an integer between 0 and RAND_MAX (=2147483647).
  2. 1.0*rand()/RAND_MAX returns a floating number between 0 and 1.
  3. 5.0*rand()/RAND_MAX returns a floating number between 0 and 5.
  4. 10.0*rand()/RAND_MAX-5 returns a floating number between −5 and 5.
  5. rand()%7 returns an integer of either 0, 1, 2, 3, 4, 5, or 6.
  6. rand()%7+10 returns an integer of either 10, 11, 12, 13, 14, 15, or 16.

Using random numbers for numerical integration (Monte Carlo Methods)



1

0 
1

x
dx = ?
buffon1.gif


2

1 
1

x
dx = ln x|12 = ln 2 − ln 1 = ln 2.
Generate a random number, x, between 1 and 2, and another random number, y, between 0 and 1. The probability that xy < 1 is proportional to ln 2/1.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

int main()
{
float x, y;
int i, count=0;
int n;

printf("Enter iteration number = ");scanf("%d", &n);

srand(time(NULL));

for (i=0; i< n; i++)
{
 x=1.0*rand()/RAND_MAX+1.0;
 y=1.0*rand()/RAND_MAX;

 if (x*y < 1.0) count=count+1;
}

printf("True value = %f\n", log(2));
printf("Appx value = %f\n", 1.0*count/n);

return 0;
}

This approach can be also applied to computing π as
buffon2.gif
As seen in the figure above, the probability that
x2+y2 < 1
if 0 < x < 1 and 0 < y < 1 should be π/4.




File translated from TEX by TTH, version 4.03.
On 11 Feb 2024, 15:21.