Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a double precision floating point number can be safely stored as a single precision one? [duplicate]

Possible Duplicate:
Real numbers - how to determine whether float or double is required?

I'm trying to check if a conversion from double to float will result in loss of precision. Obviously, I can do the conversion and convert the float back into double and compare it to the original value. I'm curious as to whether there's a more direct way.

like image 926
cleong Avatar asked Jan 14 '23 13:01

cleong


1 Answers

Converting to float and back is generally the most efficient solution; on most common architectures it will require only a couple instructions, with a latency of a couple cycles each. This also has the virtue of being both simple and correct.

On platforms that do not have hardware support for floating-point, you can do the check more efficiently by taking apart the number, and checking whether the exponent and significand fit into single-precision, but that is a relatively uncommon corner-case, and this is much more error-prone and not portable to platforms that use different FP formats.

like image 91
Stephen Canon Avatar answered Jan 27 '23 14:01

Stephen Canon