commit ee23eff931ba11a8789ed2d47b9b42802da4fa7d
parent 25e6b578888310014f5ea0b1b4d9ac6a2b46e4a6
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date: Thu, 18 Mar 2021 14:38:28 +0100
arrays.[ch]: check memory allocation and exit on fail, add some helper functions
Diffstat:
2 files changed, 40 insertions(+), 6 deletions(-)
diff --git a/arrays.c b/arrays.c
@@ -1,6 +1,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
+#include <err.h>
#define DEG2RAD(x) (x*M_PI/180.0)
@@ -72,7 +73,8 @@ linspace(const double lower, const double upper, const int n)
double dx;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
dx = (upper - lower) / (double) (n - 1);
for (i = 0; i < n; ++i)
x[i] = lower + dx * i;
@@ -88,7 +90,8 @@ spacing(const double *x, const int n)
double *dx;
check_magnitude(__func__, 2, n);
- dx = malloc((n - 1) * sizeof(double));
+ if (!(dx = calloc((n - 1), sizeof(double))))
+ err(1, "%s: dx calloc", __func__);
for (i = 0; i < n - 1; ++i)
dx[i] = x[i + 1] - x[i];
@@ -103,7 +106,8 @@ zeros(const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = malloc(n * sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = 0.0;
@@ -118,7 +122,8 @@ ones(const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = 1.0;
@@ -133,7 +138,8 @@ initval(const double value, const int n)
double *x;
check_magnitude(__func__, 1, n);
- x = malloc(n * sizeof(double));
+ if (!(x = calloc(n, sizeof(double))))
+ err(1, "%s: x calloc", __func__);
for (i = 0; i < n; ++i)
x[i] = value;
@@ -278,7 +284,8 @@ normalize(const double *in, const int n)
double *out;
check_magnitude(__func__, 1, n);
- out = malloc(n * sizeof(double));
+ if (!(out = calloc(n, sizeof(double))))
+ err(1, "%s: out calloc", __func__);
copy_values(in, out, n);
max_val = max(out, n);
@@ -290,3 +297,27 @@ normalize(const double *in, const int n)
return out;
}
+
+double
+euclidean_norm(const double *a, const int n)
+{
+ int i;
+ double out = 0.0;
+
+ for (i = 0; i < n; i++)
+ out += pow(a[i], 2.0);
+
+ return sqrt(out);
+}
+
+double
+euclidean_distance(const double *a, const double *b, const int n)
+{
+ int i;
+ double out = 0.0;
+
+ for (i = 0; i < n; i++)
+ out += pow(b[i] - a[i], 2.0);
+
+ return sqrt(out);
+}
diff --git a/arrays.h b/arrays.h
@@ -51,4 +51,7 @@ void copy_values(const double *in, double *out, const int n);
double * copy(const double *in, const int n);
double * normalize(const double *in, const int n);
+double euclidean_norm(const double *a, const int n);
+double euclidean_distance(const double *a, const double *b, const int n);
+
#endif