Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to double

How expensive is the conversion of a float to a double? Is it as trivial as an int to long conversion?

EDIT: I'm assuming a platform where where float is 4 bytes and double is 8 bytes

like image 596
Tony the Pony Avatar asked Sep 14 '09 13:09

Tony the Pony


People also ask

Can you convert a float to a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

Can you convert a float to a double in C?

You can't convert from float to double and except that float will have the same precision of double.

Is 1.5 float or double?

And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.

How do you float a double in Java?

Remember, by default floating-point numbers are double in Java, if you want to store them into float variables, you need to either cast them explicitly or suffixed them using the 'f' or 'F' characters.


2 Answers

Float to double conversions happen for free on some platforms (PPC, x86 if your compiler/runtime uses the "to hell with what type you told me to use, i'm going to evaluate everything in long double anyway, nyah nyah" evaluation mode).

On an x86 environment where floating-point evaluation is actually done in the specified type using SSE registers, conversions between float and double are about as expensive as a floating-point add or multiply (i.e., unlikely to be a performance consideration unless you're doing a lot of them).

In an embedded environment that lacks hardware floating-point, they can be somewhat costly.

like image 65
Stephen Canon Avatar answered Oct 03 '22 01:10

Stephen Canon


I can't imagine it'd be too much more complex. The big difference between converting int to long and converting float to double is that the int types have two components (sign and value) while floating point numbers have three components (sign, mantissa, and exponent).

IEEE 754 single precision is encoded in 32 bits using 1 bit for the sign, 8 bits for the exponent, and 23 bits for the significand. However, it uses a hidden bit, so the significand is 24 bits (p = 24), even though it is encoded using only 23 bits.

-- David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic

So, converting between float and double is going to keep the same sign bit, set the last 23/24 bits of the float's mantissa to the double's mantissa, and set the last 8 bits of the float's exponent to the double's exponent.

This behavior may even be guaranteed by IEEE 754... I haven't checked it, so I'm not sure.

like image 33
Powerlord Avatar answered Oct 03 '22 01:10

Powerlord