-
Notifications
You must be signed in to change notification settings - Fork 0
/
vectors-testing.c
57 lines (46 loc) · 1.38 KB
/
vectors-testing.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* Copyright (C) 2014 Tomasz Kramkowski <tk@the-tk.com>
*
* This program is free software. It is licensed under version 3 of the
* GNU General Public License.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see [http://www.gnu.org/licenses/].
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define V_NEW(l) v_new(l, (double[])
typedef struct {
int length;
double *raw;
} Vec;
double v_dot(Vec *, Vec *);
Vec *v_new(int, double *);
int main(int argc, char **argv)
{
Vec *v1 = v_new(3, (double[]){1, 2, 2});
Vec *v2 = V_NEW(3){1, 2, 3});
printf("Dot: %f\n", v_dot(v1, v2));
printf("%d: %f, %f, %f.\n", v1->length, v1->raw[0], v1->raw[1], v1->raw[2]);
printf("%d: %f, %f, %f.\n", v2->length, v2->raw[0], v2->raw[1], v2->raw[2]);
free(v1);
free(v2);
}
Vec *v_new(int length, double *raw)
{
Vec *vec = malloc(sizeof(Vec));
vec->raw = malloc(length * sizeof(double));
vec->length = length;
memcpy(vec->raw, raw, length * sizeof(double));
return vec;
}
double v_dot(Vec *v1, Vec *v2)
{
int shortest = MIN(v1->length, v2->length);
double dot = 0;
for (int i = 0; i < shortest; i++)
dot += v1->raw[i] * v2->raw[i];
return dot;
}