Home>

A function that returns the distance between an n-dimensional vector x and y, and a basic function that returns a Euclidean distance. In this case, I would like to write the most foolishly without using a library such as numpy. Specifically, this code calculates the Euclidean distance of a 3D vector.

Error message

The order was reversed, but I wrote it in "I tried it".

No error message.
Applicable source code
python3
x = [-2, 1, 6]
y = [3, -1, -2]
def ex4_4 (x, y):
    d = 0
    for i in range (0, len (x)):
        for j in range (0, len (y)):
            t = 0
            t = t + (x [i]-y [j]) ** 2
            d = t ** (1/2)
    return d


Code

In jupyter notebook
When ex4_4 (x, y) is executed, the result is 8 and it is assumed that only the last number in the list x and y is committed. I don't know why. Why isn't t added?

Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

  • Answer # 1

    Hello.

    In addition to hayataka2049's indication,

    It is a double loop, but it is not necessary to make a double loop because it only calculates the distance.

    The code after correction is written.

    x = [-2, 1, 6]
    y = [3, -1, -2]
    def ex4_4 (x, y):
        t = 0
        for i in range (0, len (x)):
            t = t + (x [i]-y [i]) ** 2
        return t ** (0.5)
    print (ex4_4 (x, y))

    The execution results are as follows

    9.643650760992955

    I hope you find it helpful.

  • Answer # 2

    T = 0 is written inside the loop.

Related articles