PI Calculation code
/* Program to compute Pi using Monte Carlo methods */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define SEED 35791246
void main(void)
{
int niter=0;
double x,y,z,pi;
int count=0; /* # of points in the 1st quadrant of unit circle */
printf("Enter the number of iterations used to estimate pi: ");
scanf("%d",&niter);
/* initialize random numbers */
srand(SEED);
count=0;
for (int i=0; i<niter; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/niter*4;
printf("# of trials= %d , estimate of pi is %g \n",niter,pi);
return 0;
}
Random Number Generator
/* */
/* This program generates and prints ten */
/* random integers between 1 and RAND_MAX. */
#include <stdio.h>
HOMEWORK:
Randon Dice Roll Generator
/* */
/* This program generates and prints ten random */
/* integers between user-specified limits. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Declare variables and function prototype. */
unsigned int seed;
int a, b, k, n;
int rand_int(int a,int b);
int count = 0;
/* Get seed value and interval limits. */
printf("Enter a positive integer seed value: \n");
scanf("%u",&seed);
srand(seed);
printf("Enter integer limits a and b (a<b) for dice roll: \n");
scanf("%i %i",&a,&b);
printf("Enter number of rolls: \n");
scanf("%i",&n);
/* Generate and print N random numbers. */
printf("Dice Rolls: \n");
for (k=1; k<=2*n; k++)
printf("%i ",rand_int(a,b));
printf("\t");
if (rand_int(a,b) + rand_int(a,b) == 8)
count++;
/* Exit program. */
return 0;
}
/* */
/* This function generates a random integer */
/* between specified limits a and b (a<b). */
int rand_int(int a,int b)
{
return rand()%(b-a+1) + a;
}
No comments:
Post a Comment