Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of floats to array of doubles in Java?

Tags:

I have an array of floats and I would like to convert it to an array of doubles in Java. I am aware of the obvious way of iterating over the array and creating a new one. I expected Java to digest a float[] smoothly where it wishes to work with double[]... but it can not work with this. What is the elegant, effective way of doing this conversion?

like image 593
fifigyuri Avatar asked Jan 07 '10 09:01

fifigyuri


People also ask

Can we convert float to double in Java?

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 make an array of doubles?

8.1 Creating arrays An array is a sequence of values; the values in the array are called elements. You can make an array of int s, double s, or any other type, but all the values in an array must have the same type.

How do you declare an array of doubles?

double m[][] declares an array of arrays, so called multidimensional array. m[0] points to an array in the size of four, containing 0*0,1*0,2*0,3*0. Simple math shows the values are actually 0,0,0,0. Second line is also array in the size of four, containing 0,1,2,3.


2 Answers

Basically something has to do the conversion of each value. There isn't an implicit conversion between the two array types because the code used to handle them after JITting would be different - they have a different element size, and the float would need a conversion whereas the double wouldn't. Compare this to array covariance for reference types, where no conversions are required when reading the data (the bit pattern is the same for a String reference as an Object reference, for example) and the element size is the same for all reference types.

In short, something will have to perform conversions in a loop. I don't know of any built-in methods to do this. I'm sure they exist in third party libraries somewhere, but unless you happen to be using one of those libraries already, I'd just write your own method. For the sake of convenience, here's a sample implementation:

public static double[] convertFloatsToDoubles(float[] input) {     if (input == null)     {         return null; // Or throw an exception - your choice     }     double[] output = new double[input.length];     for (int i = 0; i < input.length; i++)     {         output[i] = input[i];     }     return output; } 
like image 186
Jon Skeet Avatar answered Sep 23 '22 18:09

Jon Skeet


In Java 8 you can, if you really want to, do:

IntStream.range(0, floatArray.length).mapToDouble(i -> floatArray[i]).toArray(); 

But it's better (cleaner, faster, better semantics) to use Jon Skeet's function.

like image 22
Aleksandr Dubinsky Avatar answered Sep 24 '22 18:09

Aleksandr Dubinsky