Created
November 2, 2020 16:38
-
-
Save treeform/099d46b8f3ba970cb0ab6bcf17a36586 to your computer and use it in GitHub Desktop.
How to compute Binomial Coefficients in Nim (Useful as a kind of integer version of Gaussian distribution)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
# See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ | |
# for details of this function | |
func binomialCoeff(n, k: int): int = | |
var res = 1 | |
var k = k | |
if (k > n - k): | |
k = n - k | |
for i in 0 ..< k: | |
res = res * (n - i) | |
res = res div (i + 1) | |
return res | |
func binomialCoeffs(n: int): seq[int] = | |
for i in 0 .. n: | |
result.add(binomialCoeff(n, i)) | |
func binomialNormCoeffs(n: int): seq[float32] = | |
var arr = binomialCoeffs(n) | |
let total = sum(arr).float32 | |
result = newSeq[float32](arr.len) | |
for i, a in arr: | |
result[i] = a.float32 / total | |
for n in 0 ..< 50: | |
echo binomialNormCoeffs(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment