LoginSignup
7

More than 3 years have passed since last update.

ある範囲における数値を別な範囲における数値に変換する

Last updated at Posted at 2017-03-16

$ x_{min} $ 以上 $ x_{max} $ 以下の範囲に存在する数値 $ x_i $ を、0 以上 1 以下の範囲に存在する数値 $ n_i $ に変換する、つまり正規化するためには

\begin{equation}
n_i = \frac{x_i - x_{min}}{x_{max} - x_{min}}
\end{equation}

という式で計算します。逆に、正規化した数値 $ n_i $ を $ y_{min} $ 以上 $ y_{max} $ 以下の範囲に存在する数値 $ y_i $ 変換する、つまり非正規化するには、上記の式を変形した

\begin{equation}
y_i = n_i(y_{max} - y_{min}) + y_{min}
\end{equation}

という式で計算します。

module NumericExtensions
  refine Numeric do
    def normalize(min = 0, max = 1)
      (self - min).fdiv(max - min)
    end

    def denormalize(min = 0, max = 1)
      self * (max - min) + min
    end
  end
end

using NumericExtensions

# (例 1) 1..3 の範囲における 2 を 0..1 における数値に変換する。
2.normalize(1, 3) #=> 0.5

# (例 2) (例 1) の結果を元に戻す。
2.normalize(1, 3).denormalize(1, 3) #=> 2.0

# (例 3) 1..3 の範囲における 2 を 1..5 における数値に変換する。
2.normalize(1, 3).denormalize(1, 5) #=> 3.0

# (例 4) 1..5 の範囲における 3 を 1..3 における数値に変換する。
3.normalize(1, 5).denormalize(1, 3) #=> 2.0

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
7