Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistency in Floating-point to Fixed-point Conversion Across Different Platforms #69

Open
justinzhuguangwen opened this issue Nov 17, 2024 · 0 comments

Comments

@justinzhuguangwen
Copy link

I've noticed that the current implementation of the floating-point to fixed-point conversion in the code might lead to inconsistent results across different platforms. The issue stems from the direct manipulation and rounding of floating-point numbers, which can behave differently on various platforms due to differences in floating-point arithmetic implementation.

Here is the current implementation for reference:

template <typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr inline explicit fixed(T val) noexcept
    : m_value(static_cast<BaseType>((EnableRounding) ?
           (val >= 0.0) ? (val * FRACTION_MULT + T{0.5}) : (val * FRACTION_MULT - T{0.5})
          : (val * FRACTION_MULT)))
{}

Here's the suggested approach for reference:
https://github.com/SkynetNext/Fixed64/blob/main/include/Fixed64.h

template <typename T>
void parseFloat(const T &value)
{
  int64_t integerPart = static_cast<int64_t>(std::floor(value));
  T fractionalPart = value - integerPart;
  this->value = (integerPart << FixLut::PRECISION) +
                static_cast<int64_t>(fractionalPart * FixLut::ONE);
}

By first using std::floor to isolate the integer part and then handling the fractional part separately, this method avoids some of the pitfalls associated with direct floating-point arithmetic and rounding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant