Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How divide all items in an array by a double?

Tags:

java

I am a complete beginner at this and I have a little problem with an array. The point of this program is to calculate the normalization of a vector. The first part just calculates the length of the array into the int called sum and then I want to divide all the items in the array v with this sum. normal[] = v[a]/sum; this line is clearly the issue, but how should I do this??

public static double[] normalized(double[] v){

    double sum = 0;

    for(int counter = 0; counter < v.length; counter++){
        sum += Math.pow(v[counter], 2);
    }
        sum = Math.sqrt(sum);
        double[] normal;
    for(int a = 0; a < v.length; a++){      
        normal[] = v[a]/sum;
    }
return normal;
}
like image 572
George12 Avatar asked Aug 20 '13 16:08

George12


People also ask

How do you divide all elements in an array?

To divide each and every element of an array by a constant, use division arithmetic operator / . Pass array and constant as operands to the division operator as shown below. where a is input array and c is a constant. b is the resultant array.

How do you divide an array by two elements?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do you divide all numbers in an array in Python?

Iterate across all the elements in the given list using a for loop. Divide each element with the given number/divisor and append the result in the resultant list. Finally, display the resultant list after all the quotients have been calculated and appended to it.


2 Answers

All you need to do is specify an index for your normal array like so, and make sure to initialize normal:

double[] normal = new double[v.length];
for(int a = 0; a < v.length; a++)
{
  normal[a] = v[a]/sum;
}

Assuming that your sum is correct. I believe this should work.

like image 53
taronish4 Avatar answered Oct 26 '22 16:10

taronish4


There are two problems:

  • You're not initializing normal (or indeed creating an array to populate)
  • You're not specifying which element you're trying to set within normal

So you want:

double[] normal = new double[v.length];
for(int a = 0; a < v.length; a++) {
  normal[a] = v[a] / sum;
}
return normal;
like image 40
Jon Skeet Avatar answered Oct 26 '22 18:10

Jon Skeet