Ben-PH / SimpleFOC-rs

An attempt at re-writing the SimpleFOC library in rust.
MIT License
12 stars 0 forks source link

Think carefully about float usage #2

Open Ben-PH opened 4 months ago

Ben-PH commented 4 months ago

A RRIR project has some interesting opportunities with respect to types. One of them being the chance to take a step back and ask if floats are actually needed, or if some other form is preferable. Usually, if it can be solved with the type system, rust has a beautiful crate to do it with:

To illustrate, using f32 for a scale-down coeficient only has valid values 0.0 - 1.0, only 23 of the 32 bits contribute to choosing a value

// calculate the fractional component
let acc = 0.0
for bit_n in bitfield
    acc += 2^(-bit_n)

// no need to look at the exponent here

so we can throw away the 8 exponent bits, and we are left with only 23 bits of precision.

normally, that's fine, but we are in a domain where bits matter. If we use a lookup table instead of calculating sin in our hot-loops, having satisfactory resolution in the table, where 9 of every 32 bits are wasted, could be mutually exclusive on smaller platforms like the nano.

Furthermore, this gives us a 0.0000001921 resolution, but using 16 bits gives us 0.000015 resolution. if we accept this resolution, we've halved our lookup table footprint. we can halve it again if we can accept 8-bit resolution (0.004, or 0.352 degrees across 90 degrees).

Crates such as fixed give us fixed-point stuff. embedded-time offers types like MicroSeconds<uN> , and empowers you to use the type-system to your advantage.