所以我需要使用类org.apache.commons.math3.stat.StatUtils
来计算 float 组的平均值,但输入数组应该是 double 组。
如何将 float[]
转换为 double[]
?
最佳答案
您可以通过定义共同实现目标的逻辑步骤来解决问题:
- 创建一个与
float[]
长度相同的double[]
- 迭代
float[]
并将值一一保存到double[]
中的相应索引
传统上或Java 8之前的方式是这样的:
final double[] doubleArray = new double[floatArray.length];
for (int i = 0; i < floatArray.length; i++) {
doubleArray[i] = floatArray[i]; // no casting needed
}
使用Java 8时,您可以使用Stream API为了得到一个更简洁的解决方案:
IntStream.range(0, floatArray.length).forEach(index -> doubleArray[index] = floatArray[index]);
可能用作函数:
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;
}
关于java - float 数组到 double 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26357842/