So I need to use the class org.apache.commons.math3.stat.StatUtils to compute the mean of an array of float, but the input array should be an array of double.
How can I convert float[] into a double[]?
So I need to use the class org.apache.commons.math3.stat.StatUtils to compute the mean of an array of float, but the input array should be an array of double.
How can I convert float[] into a double[]?
You can solve your problem by defining logical steps that all together achieve the goal:
double[] of same length as the float[]float[] and save the values one by one in the corresponding index in the double[]
Traditionally or pre Java 8 one would go this way:
final double[] doubleArray = new double[floatArray.length];
for (int i = 0; i < floatArray.length; i++) {
doubleArray[i] = floatArray[i]; // no casting needed
}
When using Java 8 you can use the Stream API for this to get a neater solution:
IntStream.range(0, floatArray.length).forEach(index -> doubleArray[index] = floatArray[index]);
Possible use as function:
public static double[] convertToDouble(final float[] values) {
final double[] result = new double[values.length];
IntStream.range(0, values.length).forEach(index -> result[index] = values[index]);
return result;
}
Convert each value in array to double. Float is shorter than double, so You don't have to worry about losing precision.
Create array of doubles of the same length as float array. Then, You can implict convert array of float to array of double.
public double[] answer(float[] array){
double[] newArray = new double[array.length];
for ( int i = 0 ; i < array.length ; i++ )
newArray[i] = (double) array[i];
return newArray;
}