#include "dm_services.h"
#include "basics/conversion.h"
#define DIVIDER 10000
#define S2D13_MIN (-3 * DIVIDER)
#define S2D13_MAX (3 * DIVIDER)
uint16_t fixed_point_to_int_frac(
struct fixed31_32 arg,
uint8_t integer_bits,
uint8_t fractional_bits)
{
int32_t numerator;
int32_t divisor = 1 << fractional_bits;
uint16_t result;
uint16_t d = (uint16_t)dc_fixpt_floor(
dc_fixpt_abs(
arg));
if (d <= (uint16_t)(1 << integer_bits) - (1 / (uint16_t)divisor))
numerator = (uint16_t)dc_fixpt_round(
dc_fixpt_mul_int(
arg,
divisor));
else {
numerator = dc_fixpt_floor(
dc_fixpt_sub(
dc_fixpt_from_int(
1LL << integer_bits),
dc_fixpt_recip(
dc_fixpt_from_int(
divisor))));
}
if (numerator >= 0)
result = (uint16_t)numerator;
else
result = (uint16_t)(
(1 << (integer_bits + fractional_bits + 1)) + numerator);
if ((result != 0) && dc_fixpt_lt(
arg, dc_fixpt_zero))
result |= 1 << (integer_bits + fractional_bits);
return result;
}
void convert_float_matrix(
uint16_t *matrix,
struct fixed31_32 *flt,
uint32_t buffer_size)
{
const struct fixed31_32 min_2_13 =
dc_fixpt_from_fraction(S2D13_MIN, DIVIDER);
const struct fixed31_32 max_2_13 =
dc_fixpt_from_fraction(S2D13_MAX, DIVIDER);
uint32_t i;
for (i = 0; i < buffer_size; ++i) {
uint32_t reg_value =
fixed_point_to_int_frac(
dc_fixpt_clamp(
flt[i],
min_2_13,
max_2_13),
2,
13);
matrix[i] = (uint16_t)reg_value;
}
}
static uint32_t find_gcd(uint32_t a, uint32_t b)
{
uint32_t remainder = 0;
while (b != 0) {
remainder = a % b;
a = b;
b = remainder;
}
return a;
}
void reduce_fraction(uint32_t num, uint32_t den,
uint32_t *out_num, uint32_t *out_den)
{
uint32_t gcd = 0;
gcd = find_gcd(num, den);
*out_num = num / gcd;
*out_den = den / gcd;
}