Skip to content

Instantly share code, notes, and snippets.

@earthbound19
Last active July 5, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earthbound19/e4c16e3133f70ffa1d93895b5f40303b to your computer and use it in GitHub Desktop.
Save earthbound19/e4c16e3133f70ffa1d93895b5f40303b to your computer and use it in GitHub Desktop.
C randomFloatInRange executable
// DESCRIPTION
// Generates N (argv[3]) floating point numbers in range argv[1] to argv[2]. Depending on system and setup may be able to produce ~35,000N/sec.
// USAGE
// Compile for example via gcc, like this (I use an MSYS2-MinGW-64 terminal) :
// gcc randomFloatsInRange.cpp -o randomFloatsInRange.exe
// -- and then invoke the resulting executable with these parameters (POSITIONAL, not named):
// - 1. smallest possible random number to generate. I don't know the minimum; certainly 0 is allowed.
// - 2. largest possible random number to generate. Maximum may be RAND_MAX; on my system that is: 2147483648.000000.
// - 3. how many such numbers to generate. I don't know the maximum.
// Numbers are printed to standard out, one per line. Example command that will produce 1,000 numbers as small as 0.681 and as large as 1.214:
// randomFloatInRange 0.681 1.214 1000
// NOTE that if you do not pass all expected parameters, the program will not behave as expected, and won't even notify you of errors.
// CODE
// TO DO: option handling with helpful errors and help print.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// #include <unistd.h>
int main(int argc, const char *argv[]) {
// Because I noticed calling this program more than once a second resulted in the same random result, as time seeding is only at second-resolution; seed via nanoseconds; dunno why I need a timespec ts here; re: https://stackoverflow.com/a/20201185/1397555
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
srand((time_t)ts.tv_nsec);
float min = atof(argv[1]);
float max = atof(argv[2]);
char *p;
long conv = strtol(argv[3], &p, 10);
int countTo = conv;
int counter = 0;
while (counter < countTo) {
++counter;
// re https://stackoverflow.com/a/44105089/1397555
// rand() gets a random number between 0 and RAND_MAX, so dividing it by RAND_MAX gets a number between 0 and 1:
float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
// Then mathy math gives number in desired range:
float rndNumber = min + scale * (max - min); /* [min, max] */
printf("%f\n",rndNumber);
}
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment