-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfast_math.c
More file actions
53 lines (44 loc) · 1.97 KB
/
Copy pathfast_math.c
File metadata and controls
53 lines (44 loc) · 1.97 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
#include <math.h>
#include "fast_math.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
float x_to_index(float x, fast_math_function_t* fast_math_struct) {
return fast_math_struct->x2id_coef * (x - fast_math_struct->start_value);
}
float index_to_x(uint16_t index, fast_math_function_t* fast_math_struct) {
return ((float)index) * fast_math_struct->id2x_coef + fast_math_struct->start_value;
}
fast_math_function_t fast_math_init(float (*target_function)(float), float start_value, float end_value, int32_t samples_n) {
float x2id_coef = (samples_n - 1) / (end_value - start_value);
float id2x_coef = (end_value - start_value) / (samples_n - 1);
float* function_values = (float*)malloc(samples_n * sizeof(float));
fast_math_function_t fast_math_struct = {
.start_value = start_value,
.end_value = end_value,
.id2x_coef = id2x_coef,
.x2id_coef = x2id_coef,
.function_values = function_values
};
for (uint16_t index = 0; index < samples_n; index++) {
float x = index_to_x(index, &fast_math_struct);
float value = target_function(x);
function_values[index] = value;
}
return fast_math_struct;
}
float fast_math_get(float x, fast_math_function_t* fast_math_struct) {
if (x >= fast_math_struct->end_value) {
int32_t end_index = x_to_index(fast_math_struct->end_value, fast_math_struct);
return fast_math_struct->function_values[end_index];
}
else if (x <= fast_math_struct->start_value) {
int32_t start_index = x_to_index(fast_math_struct->start_value, fast_math_struct);
return fast_math_struct->function_values[start_index];
}
float index = x_to_index(x, fast_math_struct);
uint16_t index1 = (uint16_t)index;
uint16_t index2 = (uint16_t)index1 + 1;
float w = index - (float)index1;
return fast_math_struct->function_values[index1] + w * (fast_math_struct->function_values[index2] - fast_math_struct->function_values[index1]);
}