-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ3.c
More file actions
68 lines (53 loc) · 1.59 KB
/
Copy pathQ3.c
File metadata and controls
68 lines (53 loc) · 1.59 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef enum {
NUM_SUCCESS = 0,
NUM_ERR_NULL_PTR = -1,
NUM_ERR_OUT_OF_MEMORY = -2,
NUM_ERR_DIM_MISMATCH = -3
} NumError;
typedef struct {
size_t size;
double* data;
} FloatVector;
void float_vector_destroy(FloatVector* vec) {
if (vec != NULL) {
if (vec->data != NULL) {
free(vec->data);
vec->data = NULL;
}
vec->size = 0;
}
}
NumError float_vector_create(FloatVector* vec, size_t size) {
if (vec == NULL) return NUM_ERR_NULL_PTR;
vec->size = size;
vec->data = (double*)calloc(size, sizeof(double));
if (vec->data == NULL) {
float_vector_destroy(vec);
return NUM_ERR_OUT_OF_MEMORY;
}
return NUM_SUCCESS;
}
NumError vector_fma_compute(const FloatVector* A, const FloatVector* B, FloatVector* C) {
if (!A || !B || !C || !A->data || !B->data || !C->data) return NUM_ERR_NULL_PTR;
if (A->size != B->size || A->size != C->size) return NUM_ERR_DIM_MISMATCH;
for (size_t i = 0; i < A->size; ++i) {
C->data[i] = fma(A->data[i], B->data[i], C->data[i]);
}
return NUM_SUCCESS;
}
NumError vector_kahan_sum(const FloatVector* vec, double* result) {
if (!vec || !vec->data || !result) return NUM_ERR_NULL_PTR;
double sum = 0.0;
double compensation = 0.0;
for (size_t i = 0; i < vec->size; ++i) {
double y = vec->data[i] - compensation;
double t = sum + y;
compensation = (t - sum) - y;
sum = t;
}
*result = sum;
return NUM_SUCCESS;
}