asik / FixedMath.Net

Fixed point math C# library
Other
591 stars 126 forks source link

Converting float to Fix64 consistent across CPU architectures? #23

Closed benlabbeus closed 3 years ago

benlabbeus commented 3 years ago

Probably a dumb question but -

Would converting from a float to a Fix64 be consistent across CPU architectures?

float z = 0.123456789123f;
Fix64 x = (Fix64)z; // Always the same
asik commented 3 years ago

This is the code that does it:

        public static explicit operator Fix64(float value)
        {
            return new Fix64((long)(value * ONE));
        }

Two things happen:

The multiplication must be deterministic because the constant is a power of two (so it amounts to incrementing the exponent on the result). The float->integer cast behavior is specified as per the CLI spec.

So, I don't see how that wouldn't be deterministic.

asik commented 3 years ago

Well, except maybe for https://github.com/asik/FixedMath.Net/issues/9

It's been so long I don't really recall what the exact issue was. Just because that behavior is unspecified doesn't mean it actually varies across architectures.

benlabbeus commented 3 years ago

Totally makes sense. Thanks for the prompt response!

jpgordon00 commented 3 years ago

I needed this information too. I'm going to ship my product with FixedMath assuming that casting to and from floats are deterministic.

asik commented 3 years ago

There's an open issue about this, but I'm not willing to put in the time to research how to best address it. I'll just archive this repo so people understand that this is not actively maintained anymore. Feel free to fork and improve it.