blob: 6359c159a674d6d977a7d9e97063b847a2a96ccf (
plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Copyright (C) 2026 Richard Qin */
#ifndef VECTOR_MATH_H
#define VECTOR_MATH_H
#include <math.h>
#include "vec.h"
/* Real vectors use a double-typed struct vec. Destinations may alias inputs. */
static inline bool vector_add(struct vec *dst,
const struct vec *lhs,
const struct vec *rhs)
{
if (lhs->size != rhs->size) return false;
struct vec temporary;
vec_init(&temporary, double);
if (!vec_resize(&temporary, lhs->size)) return false;
double *result = temporary.data;
const double *left = lhs->data;
const double *right = rhs->data;
for (size_t i = 0; i < lhs->size; ++i) {
result[i] = left[i] + right[i];
}
vec_swap(dst, &temporary);
vec_destroy(&temporary);
return true;
}
static inline bool vector_sub(struct vec *dst,
const struct vec *lhs,
const struct vec *rhs)
{
if (lhs->size != rhs->size) return false;
struct vec temporary;
vec_init(&temporary, double);
if (!vec_resize(&temporary, lhs->size)) return false;
double *result = temporary.data;
const double *left = lhs->data;
const double *right = rhs->data;
for (size_t i = 0; i < lhs->size; ++i) {
result[i] = left[i] - right[i];
}
vec_swap(dst, &temporary);
vec_destroy(&temporary);
return true;
}
static inline bool vector_cosine(const struct vec *lhs,
const struct vec *rhs,
double *result)
{
if (lhs->size != rhs->size) return false;
double dot = 0.0;
double norm_lhs = 0.0;
double norm_rhs = 0.0;
for (size_t i = 0; i < lhs->size; ++i) {
double left = ((const double *)lhs->data)[i];
double right = ((const double *)rhs->data)[i];
dot += left * right;
norm_lhs += left * left;
norm_rhs += right * right;
}
if (norm_lhs == 0.0 || norm_rhs == 0.0) return false;
*result = dot / (sqrt(norm_lhs) * sqrt(norm_rhs));
return true;
}
#endif /* VECTOR_MATH_H */
|