MikeLankamp / fpm

C++ header-only fixed-point math library
https://mikelankamp.github.io/fpm
MIT License
650 stars 79 forks source link

Howto cast from "fpm::fixed_a_b" to "fpm::fixed_c_d" ? #9

Closed Klummel69 closed 3 years ago

Klummel69 commented 3 years ago

Is it possible to cast from e.g. fixed_8_24 to fixed_16_16 without an intermediate step via a float value?

With simple assignments "fixed2 = fixed1" the compiler reports an _>no known conversion for argument 1 from 'fpm::fixed_824' ... to 'const fpm::fixed<int, long long int, 16>&'

There is a function from_fixed_point(T value), but i dont understand it. I would have expected that the value is corrected by the difference of the FractionBits between new and old datatype.

MikeLankamp commented 3 years ago

Hi @Klummel69, this is not possible at the moment, but it makes sense to be able to do that.

However, the point of fpm is to be explicit about conversions that potentially throw away information so this functionality should be added as an explicit constructor so you can write:

fixed2 = fpm::fixed_16_16(fixed1);
Klummel69 commented 3 years ago

Great, thanks for adding the feature. This increases the quality of the library.

I plan to store data types with different solutions.

This keeps angle calculations more accurate. Only after trigonometric calculations the resolution is reduced.

Example:

    fpm::fixed_8_24 w {1.047197551};
    fpm::fixed_16_16 x,y;
    //w = w1+w2+w3;
    x = 100 * fpm::fixed_16_16(fpm::sin(w));
    y = 100 * fpm::fixed_16_16(fpm::cos(w));

A possibility of conversion without explicit construction would be good, but it is bearable.

MikeLankamp commented 3 years ago

A possibility of conversion without explicit construction would be good.

I understand the desire to have this, but it's generally a bad idea. The C++ Core Guidelines also discourage this: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions

Hence the decision to have these kind of conversions explicit.

Klummel69 commented 3 years ago

You got me. Actually, I try to follow the guideline. I had used template code that was not compliant with the guideline. In the meantime I have corrected that. Thanks.