Last active
October 14, 2022 08:29
-
-
Save stokito/ef2f9aa58de95ae5a22a11879e0a53dc to your computer and use it in GitHub Desktop.
golang fast float rounding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.h-schmidt.net/FloatConverter/IEEE754.html | |
// simplest rounding is just removing right bits from mantisa | |
func fastFloatRound(f float32) float32 { | |
fbits := math.Float32bits(f) | |
fbits = fbits >> 15 | |
fbits = fbits << 15 | |
fRounded := math.Float32frombits(fbits) | |
return fRounded | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func Test_fastFloatRound(t *testing.T) { | |
assert.Equal(t, float32(10.09375), fastFloatRound(10.1234567)) | |
assert.Equal(t, float32(99840), fastFloatRound(99999.123456789)) | |
assert.Equal(t, float32(3.3961775e+38), fastFloatRound(math.MaxFloat32)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment