2

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[]?

1

2 Answers 2

1

You can solve your problem by defining logical steps that all together achieve the goal:

  • Create a double[] of same length as the float[]
  • Iterate over the 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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.