Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created July 14, 2014 02:59
Show Gist options
  • Save fearofcode/247e27abe981d8d474ef to your computer and use it in GitHub Desktop.
Save fearofcode/247e27abe981d8d474ef to your computer and use it in GitHub Desktop.
two exercises from Sedgewick's Algorithms in C
/* exercises, chapter 3, section 1 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
gsl_rng * r;
void exercise_3_1_1() {
printf("minimum int: %d\n", INT_MIN);
printf("maximum int: %d\n\n", INT_MAX);
printf("minimum long int: %ld\n", LONG_MIN);
printf("maximum long int: %ld\n\n", LONG_MAX);
printf("minimum short int: %d\n", SHRT_MIN);
printf("maximum short int: %d\n\n", SHRT_MAX);
printf("minimum float: %e\n", -FLT_MAX);
printf("maximum float: %e\n\n", FLT_MAX);
printf("minimum double: %e\n", -DBL_MAX);
printf("maximum double: %e\n\n", DBL_MAX);
printf("minimum long double: %Lg\n", -LDBL_MAX);
printf("maximum long double: %Lg\n", LDBL_MAX);
}
int random_integer_system(int max) {
return gsl_rng_uniform_int(r, max);
}
void exercise_3_1_2() {
gsl_rng_env_setup();
r = gsl_rng_alloc (gsl_rng_default);
gsl_rng_set(r, time(NULL));
int maxes[] = {10, 100, 1000};
int counts[] = {1000, 10000, 100000, 1000000, 10000000, 100000000};
for(int max_idx = 0; max_idx < ARRAY_SIZE(maxes); max_idx++) {
for(int count_idx = 0; count_idx < ARRAY_SIZE(counts); count_idx++) {
int max = maxes[max_idx];
int count = counts[count_idx];
int random_integer = 0;
double moment1 = 0.0;
double moment2 = 0.0;
for(int i = 0; i < count; i++) {
random_integer = random_integer_system(max);
moment1 += ((double) random_integer)/count;
moment2 += ((double) random_integer*random_integer)/count;
}
double standard_deviation = sqrt(moment2 - moment1*moment1);
printf("For 0-%d, count = %d: average = %f, standard deviation = %f\n", max-1, count, moment1, standard_deviation);
}
}
gsl_rng_free (r);
}
int main() {
exercise_3_1_2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment