commit 8c9298b2b8694b8b32fa5c182299a6eab7706ebc
parent 932c3cef20eeebc528abd5e545959f8c04f305a0
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date: Tue, 3 May 2022 15:13:40 +0200
begin implementing randnum
Diffstat:
A | randnum.c | | | 71 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 71 insertions(+), 0 deletions(-)
diff --git a/randnum.c b/randnum.c
@@ -0,0 +1,71 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <limits.h>
+#include <string.h>
+#include <math.h>
+
+#include "arg.h"
+#include "util.h"
+
+char *argv0;
+
+static void
+usage(void)
+{
+ errx(1, "usage: %s [-f fmtstr] [-h] [-n num] [-s] "
+ "val1 [val2 ...]\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ int i, ret, n = 1, N;
+ double val = 0.0, *weights = NULL;
+ char fmtstr[PATH_MAX] = "%g\n";
+
+ if (pledge("stdio", NULL) == -1)
+ err(2, "pledge");
+
+ ARGBEGIN {
+ case 'f':
+ ret = snprintf(fmtstr, sizeof(fmtstr), "%s", EARGF(usage()));
+ if (ret < 0 || (size_t)ret >= sizeof(fmtstr))
+ errx(1, "%s: could not write fmtstr", __func__);
+ break;
+ case 'h':
+ usage();
+ break;
+ case 'n':
+ n = atoi(EARGF(usage()));
+ break;
+ default:
+ usage();
+ } ARGEND;
+
+ if (argc < 1)
+ usage();
+
+ N = argc;
+ if (!(weights = calloc(N, sizeof(double))))
+ err(1, "calloc");
+
+ for (i = 0; i < N; i++) {
+ weights[i] = atof(argv[i]);
+ if (weights[i] <= 0.0)
+ errx(1, "weight %d is not positive (%g)", i, weights[i]);
+ if (weights[i] > 1.0)
+ errx(1, "weight %d is greater than 1 (%g)", i, weights[i]);
+ }
+ val = 0.0;
+ for (i = 0; i < N; i++)
+ val += weights[i];
+ if (fabs(val - 1.0) > 1e-3)
+ errx(1, "weights do not sum to 1 (%g)", val);
+
+
+
+ free(weights);
+
+ return 0;
+}