【问题标题】:Converting mathematical formula into node.js将数学公式转换为 node.js
【发布时间】:2018-08-27 13:10:02
【问题描述】:

我想使用此处列出的数学公式:

https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets

在 node.js 中计算我可以使用k 字符生成n 长度的唯一环序列的总数,允许重复并忽略镜像序列

这个公式需要前面的公式也计算出来,如下所示:

https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_necklaces

这个“项链数量”公式的结果在“手镯数量”公式中用作Nk(n)

编辑

这是最终的解决方案:

const phi = require('number-theory').eulerPhi
const divisors = require('number-theory').divisors

let n = 6,
  k = 5,
  sum = (arr, func) => arr.reduce( (acc, n) => acc + func(n), 0),
  divisorsArray = divisors(n),
  necklaces = (1/n) * sum(divisorsArray, (d) => phi(d) * k ** (n/d))

let bracelets = (n % 2) ?
  (necklaces/2) + 0.5 * (k ** ((n+1)/2)) :
  (necklaces/2) + 0.25 * (k+1) * (k ** (n/2))

【问题讨论】:

  • 你可以使用这样的数学库:github.com/arguiot/TheoremJS
  • 感谢您的提示,但我对数学公式的理解还不够,甚至无法开始了解如何将其转换为 TheoremJS 或任何类型的 js?有什么建议吗?
  • 公式我也不懂^^。我可以向你展示如何在 js 中创建一个 sum(这将是一个好的开始): const sum = (nStart, nEnd, myFunction) => { return Array.from(Array(nEnd - nStart)) // 创建一个空x 元素数组 .reduce((acc, item, n) => acc + myFunction(n)) // 检查 reduce 函数 } sum(0, 100, n => n + 1)
  • en.m.wikipedia.org/wiki/Summation#Capital-sigma_notation 这个对 sigma 符号的解释最终准确地描述了让你感到困惑的用法。
  • 关于数学符号的问题可能会在Mathematics 上得到更好的答案。正如您在此处所做的那样,准确提及您不理解的部分总是有帮助的。

标签: javascript node.js math formula bioinformatics


【解决方案1】:

这是最终的解决方案,对我来说是正确的

const phi = require('number-theory').eulerPhi
const divisors = require('number-theory').divisors

let n = 6,
    k = 5,
    sum = (arr, func) => arr.reduce( (acc, n) => acc + func(n), 0),
    divisorsArray = divisors(n),
    necklaces = (1/n) * sum(divisorsArray, (d) => phi(d) * k ** (n/d))

let bracelets = (n % 2) ?
    (necklaces/2) + 0.5 * (k ** ((n+1)/2)) :
    (necklaces/2) + 0.25 * (k+1) * (k ** (n/2))

【讨论】:

  • 如对您问题的评论中所述,如果您正确计算了总和,则不需要 Math.floor :)
  • 这似乎不对,如果我从总和中删除 arr[0],对于 k:5,n:5,我得到 64,但如果我把 arr[0] 放回去,我得到 377 (正确答案)
  • 解决方案不仅仅是删除arr[0](这会给你一个不同的错误值)。您需要将其替换为 0。
  • 啊对,我的错,谢谢,更新了我的代码以反映这一点
  • 或者,necklaces = divisorsArray.map(d => phi(d) * k ** (n/d)).reduce((a,n) => a+n) / n。 (在这种情况下,最好在最后进行除法,因为该计算是精确的,而1/n 不是除了 2 的幂。)reduce/map 习惯用法在 map 是生成器的语言(如 Python)中效果更好;在 JS 中,map 会创建一个临时数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多