LoginSignup
0
0

More than 1 year has passed since last update.

ユークリッドノルムで遊んだ

Last updated at Posted at 2022-04-08

ユークリッド距離の定義

ユークリッド空間上に定義された2つの座標$A,B$を以下のように定義します。

\begin{align}
A&=
\begin{pmatrix}
a_1 & a_2 &\cdots &a_{n-1} & a_n
\end{pmatrix}\\
B&=
\begin{pmatrix}
b_1 & b_2 & \cdots &b_{n-1} & b_n
\end{pmatrix}
\end{align}

このように定義すると2つの座標間のユークリッド距離は次のように与えられます。

\begin{align}
d=\sqrt{(a_1 - b_1)^2+(a_2 - b_2)^2 + \cdots +(a_{n-1} - b_{n-1})^2+(a_n - b_n)^2}= \sqrt{\sum_{i=1}^n (a_i - b_i)^2}
\end{align}

C言語での実装

素直に作る

まず素直にC言語での実装すると次のようになります。

#include<stdio.h>
#include<math.h>

double norm(double*, double*, int, int);

int main(int argc, char* argv[]) {


    double p1[] = { 0,0};
    double p2[] = { 0,10};

    double d;

    int arrayNumber1 = sizeof p1 / sizeof p1[0];
    int arrayNumber2 = sizeof p2 / sizeof p2[0];

    d = norm(p1, p2, arrayNumber1, arrayNumber2);

    printf("norm -> %f", d);
    return 0;
}

double norm(double* p1, double* p2, int arrayNumber1, int arrayNumber2) {
    if (arrayNumber1 == arrayNumber2) {
        int i;
        double num = 0;
        for (i = 0; i < arrayNumber1; i++) {
            num = num + pow((p1[i] - p2[i]), 2.0);
        }

        printf("%f", num);
        return sqrt(num);
    }
    else {
        return -1;
    }
}

norm関数内でfor文をくるくる回して計算しています。norm関数内部のif文はエラー処理で、$A,B$の配列の長さが異なる場合エラーを返します。

if (arrayNumber1 == arrayNumber2)

再帰呼び出しで作る

次にこれを再帰呼び出しで作るとこのようになります。multiplication関数が何度も呼び出され結果がsumに加算されていきます。

#include<stdio.h>
#include<math.h>

double norm(double*, double*, int, int);
void multiplication(double*, double*, int, double*);

int main(int argc, char* argv[]) {


    double p1[] = { 0,0 };
    double p2[] = { 1,1 };

    double d;

    int arrayNumber1 = sizeof p1 / sizeof p1[0];
    int arrayNumber2 = sizeof p2 / sizeof p2[0];

    d = norm(p1, p2, arrayNumber1, arrayNumber2);

    printf("norm -> %f", d);
    return 0;
}

double norm(double* p1, double* p2, int arrayNumber1, int arrayNumber2) {
    if (arrayNumber1 == arrayNumber2) {
        double num = 0;
        int n = arrayNumber1 - 1;
        multiplication(p1, p2, n, &num);
        printf("%f", num);
        return sqrt(num);
    }
    else {
        return -1;
    }
}
void multiplication(double* p1, double* p2, int n, double* num) {
    if (n == 0) {
        *num = *num + pow(p1[0] - p2[0], 2.0);
    }
    else {
        multiplication(p1, p2, n - 1, num);
        *num = *num + pow(p1[n] - p2[n], 2.0);
    }
}

参考

Wikipedia ユークリッド距離

しろねこらぼ(ブログ)

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0