Floating point serialization, lexicographical comparison == floating point comparison

安稳与你 提交于 2019-12-08 03:35:02

问题


I'm looking for a way to serialize floating points so that in their serialized form a lexicographical comparison is the same as a floating point comparison. I think it is possible by storing it in the form:

| signed bit (1 for positive) | exponent | significand |

The exponent and the significand would be serialized as big-endian and the complement would be taken for negative numbers.

Would this work? I don't mind if it breaks for NaN, but having INF comparison working would be nice.


回答1:


The format of IEEE numbers are specifically designed so that "plain" integer comparison could be used. However, this only applies when two numbers of the same sign is compared.

Your suggestion to complement the numbers when they are negative is sound, so this will work.

This will work for +-Inf:s and for subnormal numbers. NaN:s, however, will not work, or rather, they will be considered "larger" than inf:s.

The only problematic case is "-Zero" (i.e. sign=1, exponent=0, and mantissa=0). Accoring to IEEE, Zero == -Zero. You have to decide if you want to emit -Zero as Zero, treat them as different, or add special code to the comparison routine.



来源:https://stackoverflow.com/questions/5243091/floating-point-serialization-lexicographical-comparison-floating-point-compa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!