Distance formula with arrays, and loops. help?

Question 5: Calculate Distance (15 points)

The final method you should write will involve a comparison of two arrays to calculate how similar they are to each other. Write a method called calculateDistance which takes as input two double[] and returns a double representing the Euclidean distance between the two arrays.

The Euclidean distance can be computed by first calculating the sum of the square distances between the two arrays and then taking the square root of the entire thing (essentially the Pythagorean theorem). For example, if your arrays are acalled array1 and array2 and had size of 3 you could calculate the Euclidean distance by the following:

sqrt(array1[0] − array2[0])2 + (array1[1] − array2[1])2 + (array1[2] − array2[2])

Since you don’t know ahead of time how large the arrays will be, however, you need to use a loop. Your

method should return this Euclidean distance.

Your method may assume for simplicity that the size of the arrays will always be the same. That is, you do not need to add extra logic to handle that case.

how do I start this? and how would I use a loop in this situation?

all i know is this formula

double distance = Math.sqrt(Math.pow((array1[x] - array2[x]),2))

Thank you!!

Re: Distance formula with arrays, and loops. help?

Quote:

Originally Posted by

**smith999**
...

... how would I ...

I don't get much out of the statement about Euclidean distance, so I'll try to express it in a way that makes sense to me.

In words: The Euclidean distance between two numerical arrays of equal length is equal to the square root of the sum of the squares of the differences between corresponding array elements.

It's actually easier to do than it is to talk about, and pseudo-code may be more clear than my words.

Anyhow...

See whether you think the following few lines of pseudo-code make sense according to the definition of Euclidean distance. If the pseudo-code makes sense, then implementation with Java is a snap. If it doesn't make sense to you, then you must think about it until it does!

(Just kidding. If there are questions, it's always OK to ask. But think about it first.)

Code :

This assumes that the two arrays are the same length, as your assignment stipulates.
Declare a double precision variable, sumSquares. Initialize sumSquares to 0.0;
Repeat the following loop for integer values of k from 0 through the index of the last element of the arrays:
BEGIN LOOP
Add the square of (array1[k]-array2[k]) to sumSquares
END LOOP
Then take the square root of sumSquares. That's the Euclidean distance between the two arrays
Taa-Daa!

Cheers!

Z