gpt4 book ai didi

java - 有两种方法,具有相同的数组,用于转换数组元素的合理公式。方法返回不同的值

转载 作者:行者123 更新时间:2023-12-01 19:55:07 26 4
gpt4 key购买 nike

有两种方法,使用相同的数组,转换数组元素的公式相同。方法返回不同的值。

数组大小:

private static final int SIZE = 10000000;
private static final int h = SIZE/2;

第一种方法:数组填充1,用新公式计算新值

  private static float[] method1() {
float arr[] = new float[SIZE];

//array fill with 1,
for (int i = 0; i < arr.length; i++) {
arr[i] = 1;
}


//calulate new values with new formula
for (int i = 0; i < arr.length; i++) {
arr[i] = (float) (i * Math.sin(0.2f + i / 5) *
Math.cos(0.2f + i / 5) *
Math.cos(0.4f + i / 2));

}
//return new value
return arr;
}

第二种方法:将数组分成两个长度相同的 arr/2,分别计算每个结果编译回一个

 private static float[] method2(){
float arr[] = new float[SIZE];

float firstarr[] = new float[h];

float secondarr[] = new float[h];

float result[] = new float[SIZE];

for (int i = 0; i <arr.length ; i++) {
arr[i] = 1;
}
//Devide array in two with same length arr/2,
System.arraycopy(arr, 0, firstarr, 0, h);
System.arraycopy(arr, h, secondarr, 0, h);


for (int i = 0; i < firstarr.length; i++) {
firstarr[i] = (float) (i * Math.sin(0.2f + i / 5) *
Math.cos(0.2f + i / 5) *
Math.cos(0.4f + i / 2));
}

for (int i = 0; i < secondarr.length; i++) {
secondarr[i] = (float) (i * Math.sin(0.2f + i / 5)
* Math.cos(0.2f + i / 5)
* Math.cos(0.4f + i / 2));
}
//compile back in one

System.arraycopy(firstarr, 0, result, 0, h);
System.arraycopy(secondarr, 0, result, h, h);

// return result
return result;

}

计算数组元素的数量

    private static long amount(float[] arr){
long result = 0;

for (int i = 0; i <arr.length ; i++) {
result += arr[i];
}
return result;
}




public static void main(String[] args) {
System.out.println(amount(method1()));// ammount for first method: 22527562

System.out.println(amount(method2())); // ammount for second method: -20047478

}}

方法 1 和方法 2 的结果应该相同。 我哪里做错了?为什么返回值不同?

最佳答案

你的问题是循环的。第一种方法从 0 到 N 循环 i。第二种方法从 i 到 N/2 循环两次。

例如:对于 N = 4 第一个方法返回您

i=0 0.0 
i=1 0.17....
i=2 0.066....
i=3 0.099....

但是第二个:

i=0 0.0 
i=1 0.17....
i=0 0.0
i=1 0.17....

所以可能的解决方案是像这样改变第二个循环

    for (int i = h; i < SIZE; i++) {
secondarr[i-h] = (float) (i * Math.sin(0.2f + i / 5)
* Math.cos(0.2f + i / 5)
* Math.cos(0.4f + i / 2));
}

关于java - 有两种方法,具有相同的数组,用于转换数组元素的合理公式。方法返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com