漂浮[]差异

时间:2011-05-08 01:16:05

标签: java

我想知道找到两个浮点数组之间差异的绝对值的最有效方法是什么?

是否如下:

private float absDifference(float[] vector1, float[] vector2) {
    float difference=0;
    int len=Math.max(vector1.length, vector2.length);
    for(int n=0;n<len;n++){
        float diff=0;
        if(n<vector1.length){
            diff+=vector1[n];
        }
        if(n<vector2.length){
            diff-=vector2[n];
        }
        difference+=Math.abs(diff);
    }
    return difference;
}

1 个答案:

答案 0 :(得分:2)

private float absDifference(float[] vector1, float[] vector2) {
    float difference=0;
    int len=Math.min(vector1.length, vector2.length);
    for(int n=0;n<len;n++){
            diff+=vector1[n]-vector2[n];
        difference+=Math.abs(vector1[n]-vector2[n]);
    }
    if(vector1.length > vector2.length){
        for(;n<vector1.length;n++){
            difference+=Math.abs(vector1[n]);
       }
    }else{
       for(;n<vector2.length;n++){
           difference+=Math.abs(vector2[n]);
       }
    }
    return difference;
}

这样在第一个循环内没有重复的边界检查,之后更长的数组的其余部分被单独处理