In the method normalize
I input an array say, {1, 2, 3, 4}
, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}
.
I know I should introduce a new array in the method (b
in the following), but why actually?
public static double[] normalize(double[] a) {
double[] b = new double[a.length];
double sum = 0;
for (int i = 0; i < b.length; i++) {
sum += a[i];
}
for (int i = 0; i < b.length; i++) {
b[i] = a[i]/sum;
}
return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
Why is the following wrong:
public static double[] normalize(double[] a) {
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
for (int i = 0; i < a.length; i++) {
a[i] = a[i]/sum;
}
return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4