如何在 vega 公式变换中使用阶乘 (!)

How do I use factorial (!) in a vega formula transform

我正在尝试使用 vega js 规范创建 binomial distribution PMF 的直方图。

这通常是如何完成的? vega expressions does not include functions for choose, or factorial, nor does it include a binomial distribution under the statistical functions.

我似乎也无法引用 vega 规范中的其他函数(即下面的 yval)。

  "data":[
{"name": "dataset",
"transform": [
  {"type":"sequence", "start": 1, "stop": 50, "step": 1, "as": "seq" },
  {"type": "formula", "as": "xval", "expr": "if(datum.seq<nval,datum.seq,NaN)"},
  {"type": "formula", "as": "yval", "expr": "math.factorial(datum.xval)
  " }
]}],

谢谢。

没有可用的阶乘运算,但如果需要更高的精度,一种合适的选择可能是用 Stirling's approximation, or perhaps a Stirling series 来近似它。

例如,在 Vega-Lite (view in editor) 中:

{
  "data": {
    "values": [
      {"n": 0, "factorial": 1},
      {"n": 1, "factorial": 1},
      {"n": 2, "factorial": 2},
      {"n": 3, "factorial": 6},
      {"n": 4, "factorial": 24},
      {"n": 5, "factorial": 120},
      {"n": 6, "factorial": 720},
      {"n": 7, "factorial": 5040},
      {"n": 8, "factorial": 40320},
      {"n": 9, "factorial": 362880},
      {"n": 10, "factorial": 3628800}
    ]
  },
  "transform": [
    {
      "calculate": "datum.n == 0 ? 1 : sqrt(2 * PI * datum.n) * pow(datum.n / E, datum.n)",
      "as": "stirling"
    },
    {"fold": ["factorial", "stirling"]}
  ],
  "mark": "point",
  "encoding": {
    "x": {"field": "n", "type": "quantitative"},
    "y": {"field": "value", "type": "quantitative", "scale": {"type": "log"}},
    "color": {"field": "key", "type": "nominal"}
  }
}