将双精度数组转换为单精度浮点数数组。

13
我有一个double[][]数组,想要将其中一行转换成float[]数组。起初尝试强制类型转换失败后,我寻找了其他方法。
我在stackoverflow上找到了一种优雅的解决方案,可以将Object[]转换为String[],如果我将Object[]转换为float[]也同样适用。
所以:是否有一种优雅的方法将double[]转换为float[],或者将double[]转换为Object[],以便我可以使用其他帖子中的代码?
我将提供一个示例代码,即使我认为这不是必要的:
double[][] datos = serie.toArray();
double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}};
double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length);
// This would be great but doesn't exist:
//float[] floatArray = Arrays.copyOf(doubleArray, doubleArray.length, float[].class);
7个回答

36
不,将数组强制转换类型是不行的。你需要显式地转换每个元素:
float[] floatArray = new float[doubleArray.length];
for (int i = 0 ; i < doubleArray.length; i++)
{
    floatArray[i] = (float) doubleArray[i];
}

9

这是一个函数,你可以将它放在库中并反复使用:

float[] toFloatArray(double[] arr) {
  if (arr == null) return null;
  int n = arr.length;
  float[] ret = new float[n];
  for (int i = 0; i < n; i++) {
    ret[i] = (float)arr[i];
  }
  return ret;
}

使用 System.arrayCopy。 - Mark Renouf

4

供日后参考;这也可以通过使用Guava更加简洁地完成,如下所示:

double[] values = new double[]{1,2,3};

float[] floatValues = Floats.toArray(Doubles.asList(values));

3
看起来很慢(可能不是,只是觉得它看起来很慢)。你有测试过吗? - kritzikratzi
不,我没有测试运行时间。它可能不像编写循环那样快,但如果你不经常这样做和/或针对大型列表,它仍然不应该花费太多时间。 - Pieter-Paul Kramer
8
好的,我测试了一下。在我的机器上,速度慢了大约9倍。http://pastebin.com/Rh5eWY7q 在我看来,这个东西不应该被使用。虽然代码行数少了一个,但它更慢、更复杂,并且需要一个巨大的依赖项。 - kritzikratzi
1
感谢您付出测试性能的努力。我同意仅为此目的包含Guava有些过头,但如果您已经在使用它,我认为这比循环更清晰。不是因为它节省了两行(而不是一行),而是因为它避免了循环本身。当然,这是主观的,但在我看来,循环通常是复杂性的指示,在阅读代码时值得关注。这就是为什么我更喜欢我发布的片段。正如我所解释的,我通常不会真正关心这样一个函数的性能,并且我不认为这比循环更加复杂。 - Pieter-Paul Kramer

4
使用Kotlin可以尝试以下操作:
 val doubleArray = arrayOf(2.0, 3.0, 5.0)
 val floatArray = doubleArray.map { it.toFloat() }.toFloatArray()

或者

 val floatArray = arrayOf(2.0, 3.0, 5.0).map { it.toFloat() }.toFloatArray()

2

我创建了这个类只是为了自己的使用,但我认为它可以帮助你解决问题。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ArrayUtils {

    private static final Logger log = LoggerFactory.getLogger(ArrayUtils.class);
    private static final Map<Class, Class> primitiveMapping = new HashMap<Class, Class>();
    private static final Map<Class, Method> primitiveParseMethodLookup = new HashMap<Class, Method>();
    private static final Map<Class, Method> primitiveArrayGetMethodLookup = new HashMap<Class, Method>();
    private static final Map<Class, Method> valueOfMethodLookup = new HashMap<Class, Method>();

    static {

        // Initialize primitive mappings
        primitiveMapping.put(boolean.class, Boolean.class);
        primitiveMapping.put(byte.class, Byte.class);
        primitiveMapping.put(short.class, Short.class);
        primitiveMapping.put(int.class, Integer.class);
        primitiveMapping.put(float.class, Float.class);
        primitiveMapping.put(long.class, Long.class);
        primitiveMapping.put(double.class, Double.class);

        // Initialize parse, valueOf and get method lookup
        // We do that in advance because the lookup of the method takes the longest time
        // Compared to the normal method call it's 20x higher
        // So we use just the reflective method call which takes double the time of a normal method call
        try {
            primitiveParseMethodLookup.put(boolean.class, Boolean.class.getMethod("parseBoolean", new Class[]{String.class}));
            primitiveParseMethodLookup.put(byte.class, Byte.class.getMethod("parseByte", new Class[]{String.class}));
            primitiveParseMethodLookup.put(short.class, Short.class.getMethod("parseShort", new Class[]{String.class}));
            primitiveParseMethodLookup.put(int.class, Integer.class.getMethod("parseInt", String.class));
            primitiveParseMethodLookup.put(float.class, Float.class.getMethod("parseFloat", String.class));
            primitiveParseMethodLookup.put(long.class, Long.class.getMethod("parseLong", String.class));
            primitiveParseMethodLookup.put(double.class, Double.class.getMethod("parseDouble", String.class));

            valueOfMethodLookup.put(Boolean.class, Boolean.class.getMethod("valueOf", new Class[]{String.class}));
            valueOfMethodLookup.put(Byte.class, Byte.class.getMethod("valueOf", new Class[]{String.class}));
            valueOfMethodLookup.put(Short.class, Short.class.getMethod("valueOf", new Class[]{String.class}));
            valueOfMethodLookup.put(Integer.class, Integer.class.getMethod("valueOf", String.class));
            valueOfMethodLookup.put(Float.class, Float.class.getMethod("valueOf", String.class));
            valueOfMethodLookup.put(Long.class, Long.class.getMethod("valueOf", String.class));
            valueOfMethodLookup.put(Double.class, Double.class.getMethod("valueOf", String.class));

            primitiveArrayGetMethodLookup.put(boolean.class, Array.class.getMethod("getBoolean", new Class[]{Object.class, int.class}));
            primitiveArrayGetMethodLookup.put(byte.class, Array.class.getMethod("getByte", new Class[]{Object.class, int.class}));
            primitiveArrayGetMethodLookup.put(short.class, Array.class.getMethod("getShort", new Class[]{Object.class, int.class}));
            primitiveArrayGetMethodLookup.put(int.class, Array.class.getMethod("getInt", Object.class, int.class));
            primitiveArrayGetMethodLookup.put(float.class, Array.class.getMethod("getFloat", Object.class, int.class));
            primitiveArrayGetMethodLookup.put(long.class, Array.class.getMethod("getLong", Object.class, int.class));
            primitiveArrayGetMethodLookup.put(double.class, Array.class.getMethod("getDouble", Object.class, int.class));
        } catch (NoSuchMethodException e) {

            //******************************
            // This can never happen
            //******************************
        }

    }

    public static boolean isArrayOfPrimitives(Object object) {

        if (object.getClass().isArray()) {
            return object.getClass().getComponentType().isPrimitive();
        }

        return false;
    }

    public static boolean isArrayOf(Object object, Class clazz) {

        if (object.getClass().isArray()) {
            return clazz.isAssignableFrom(object.getClass().getComponentType());
        }

        return false;
    }

    /**
     * Convert any array of primitives(excluding char), strings or numbers into any other array
     * of strings or numbers.
     *
     * @param array                       Array of primitives(excluding char), strings or numbers
     * @param convertedArrayComponentType Converted array component type (String or Number)
     * @param <T>                         To allow implicit casting
     * @return Array of convertedArrayComponentType
     */
    public static <T> T[] convertArray(Object array, Class<T> convertedArrayComponentType) {

        // Collect data regarding arguments
        final boolean arrayOfPrimitives = isArrayOfPrimitives(array);
        final boolean arrayOfCharPrimitives = isArrayOf(array, char.class);
        final boolean arrayOfCharacters = isArrayOf(array, Character.class);
        final boolean arrayOfStrings = isArrayOf(array, String.class);
        final boolean arrayOfNumbers = isArrayOf(array, Number.class);

        // Check if array is an array of strings, primitives or wrapped primitives
        if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) {
            throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)");
        }

        // Check if it's assignable from Number of String
        if (!Number.class.isAssignableFrom(convertedArrayComponentType) && !String.class.isAssignableFrom(convertedArrayComponentType)) {
            throw new IllegalArgumentException(convertedArrayComponentType + " must be a Number or a String");
        }

        try {
            return (T[]) convertArrayInternal(array, convertedArrayComponentType);
        } catch (InvocationTargetException e) {

            // This can happen due to errors in conversion
            throw (RuntimeException) e.getTargetException();
        } catch (Exception e) {

            // This should never happen
            log.error("Something went really wrong in ArrayUtils.convertArray method.", e);
        }

        // To satisfy the compiler
        return null;
    }

    /**
     * Convert any array of primitives(excluding char), strings or numbers into an array
     * of primitives(excluding char).
     *
     * @param array                       Array of primitives(excluding char), strings or numbers
     * @param convertedArrayComponentType Converted array component type primitive(excluding char)
     * @return Array of convertedArrayComponentType
     */
    public static Object convertToPrimitiveArray(Object array, Class convertedArrayComponentType) {

        // Collect data regarding arguments
        final boolean arrayOfPrimitives = isArrayOfPrimitives(array);
        final boolean arrayOfCharPrimitives = isArrayOf(array, char.class);
        final boolean arrayOfCharacters = isArrayOf(array, Character.class);
        final boolean arrayOfStrings = isArrayOf(array, String.class);
        final boolean arrayOfNumbers = isArrayOf(array, Number.class);

        // Check if array is an array of strings, primitives or wrapped primitives
        if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) {
            throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)");
        }

        // Check if it's assignable from Number of String
        if (!convertedArrayComponentType.isPrimitive() || convertedArrayComponentType.isAssignableFrom(char.class)) {
            throw new IllegalArgumentException(convertedArrayComponentType + " must be a primitive(excluding char)");
        }

        try {
            return convertArrayInternal(array, convertedArrayComponentType);
        } catch (InvocationTargetException e) {

            // This can happen due to errors in conversion
            throw (RuntimeException) e.getTargetException();
        } catch (Exception e) {

            // This should never happen
            log.error("Something went really wrong in ArrayUtils.convertArray method.", e);
        }

        // To satisfy the compiler
        return null;
    }

    private static Object convertArrayInternal(Object array, Class convertedArrayComponentType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        // Lookup the primitive parse method or the boxed primitive valueOf method
        final Method convertMethod;
        if (convertedArrayComponentType.isPrimitive()) {
            convertMethod = primitiveParseMethodLookup.get(convertedArrayComponentType);
        } else {
            convertMethod = valueOfMethodLookup.get(convertedArrayComponentType);
        }

        // If the array is an array of primitives lookup the get method
        final Method primitiveArrayGetMethod = primitiveArrayGetMethodLookup.get(array.getClass().getComponentType());

        // Get length and create new array
        final int arrayLength = Array.getLength(array);
        final Object castedArray = Array.newInstance(convertedArrayComponentType, arrayLength);

        for (int i = 0; i < arrayLength; i++) {

            final Object value;
            if (primitiveArrayGetMethod != null) {
                value = primitiveArrayGetMethod.invoke(null, array, i);
            } else {
                value = Array.get(array, i);
            }

            final String stringValue = String.valueOf(value);
            final Object castedValue = convertMethod.invoke(null, stringValue);
            Array.set(castedArray, i, castedValue);
        }

        return castedArray;
    }

}

它可以像这样使用:

double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}};
double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length);
float[] floatArray = (float[]) ArrayUtils.convertToPrimitiveArray(doubleArray, float.class);

0

Swift 5

extension Collection where Iterator.Element == Float
{
    var convertToDouble: [Double]
    {
        return compactMap { Double($0) }
    }
}

extension Collection where Iterator.Element == Double
{
    var convertToFloat: [Float]
    {
        return compactMap { Float($0) }
    }
}

-1

科特林

val doubleArray = arrayOf(2.0, 3.0, 5.0)
val floatArray = FloatArray(doubleArray.size) { i -> doubleArray[i].toFloat() }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接