解释phi系数函数如何在Eloquent Javascript中工作?

时间:2014-10-12 09:03:01

标签: javascript arrays math

我正在阅读Eloquent Javascript,到目前为止,这是一个很好的阅读,但我坚持他提出的这个功能,用于计算phi-coeffcient。这是代码。

显然有相当多的背景,我无法复制/粘贴书中的所有内容,所以如果真正读过这本书的人可以向我解释这一点,那就太棒了!

我不知道的是,当他说“table [3]”或“table [0]”时会提到什么?我理解phi系数公式:

φ=(n11n00 - n10n01)/(√n1•n0•n•1n•0)

但是我(根本没有)如何将它翻译成JS。这段代码究竟发生了什么?

function phi(table) {
  return (table[3] * table[0] - table[2] * table[1]) /
    Math.sqrt((table[2] + table[3]) *
              (table[0] + table[1]) *
              (table[1] + table[3]) *
              (table[0] + table[2]));
}

1 个答案:

答案 0 :(得分:8)

尝试将每个步骤的过程可视化,并替换为等式:

┌──────────────┬──────────────┐
│ label: n00   │ label: n01   │
│ count: 76    │ count: 9     │
│ no squirrel, │ no squirrel, │
│ no pizza     │ pizza        │
├──────────────┼──────────────┤
│ label: n10   │ label: n11   │
│ count: 4     │ count: 1     │
│ squirrel,    │ squirrel,    │
│ no pizza     │ pizza        │
└──────────────┴──────────────┘
table = [n00, n01, n10, n11]

n00 = table[0] = 76
n10 = table[1] = 4
n01 = table[2] = 9
n11 = table[3] = 1

n1• = n10 + n11 = table[2] + table[3] = 9  + 1 = 10
n0• = n00 + n01 = table[0] + table[1] = 76 + 4 = 80
n•1 = n01 + n11 = table[1] + table[3] = 4  + 1 = 5
n•0 = n00 + n10 = table[0] + table[2] = 76 + 9 = 85

//pseudo code
phi = function(table) {
  return (n11 * n00 - n10 * n01) /
    Math.sqrt(n1• * n0• * n•1 * n•0)
}

//JavaScript code
phi = function(table) {
  return (table[3] * table[0] - table[2] * table[1]) /
    Math.sqrt((table[2] + table[3]) *
              (table[0] + table[1]) *
              (table[1] + table[3]) *
              (table[0] + table[2]))
}