1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

reduce使えばJavaScriptで簡単に線形補間できる

Posted at

簡単に線形補間する方法

reduceを使えば、ある数値が昇順に並んだ配列の何番目と何番目の間かがすぐわかります。

const index= x.reduce((pre,current,i)=>current <= x0 ? i : pre, 0)

これにより、線形補間を簡単に計算できます。

const linear = (x, y)=>{
  return (x0)=>{
    const index= x.reduce((pre,current,i)=>current <= x0 ? i : pre, 0) //数値が何番目の配列の間かを探す
    const i = index === x.length-1 ? x.length-2 : index //配列の最後の値より大きい場合は、外挿のために、最後から2番目をindexにする

    return (y[i+1]-y[i])/(x[i+1]-x[i])*(x0-x[i])+y[i] //線形補間の関数を返す
  } 
}

const x = [0,1,2,3,4,5] 
const y = [0,2,4,6,8,10]
const linear0 = linear(x,y) //線形補間関数を作成

const x0 = 2.5 
const y0 = linear0(x0) 
console.log(y0) // -> 5

jsnoteにコードを張り付けてで試してみてください。

Imgur

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?