Skip to content

Instantly share code, notes, and snippets.

@dimavs
Last active August 9, 2018 05:02
Show Gist options
  • Save dimavs/b1b1d0717fe3fd6c610a029bc07f4085 to your computer and use it in GitHub Desktop.
Save dimavs/b1b1d0717fe3fd6c610a029bc07f4085 to your computer and use it in GitHub Desktop.
#!/bin/bash
display_usage() {
echo -e "Usage:\n\t$0 <p> <n> <x>\n"
}
if [ $# -le 2 ]; then
display_usage
exit 1
fi
bc << EOF
define ncx(n, x)
{
auto a, b, i
a = 1
for(i = (x + 1); i <= n; i++)
{
a *= i;
}
b = 1
for(i = 1; i <= (n - x); i++)
{
b *= i;
}
return a / b
}
define binprob(p, n, x)
{
auto v
v = ncx(n, x)
v *= (1 - p) ^ (n - x)
v *= p ^ x
return v
}
define r(x, d)
{
auto r, s
if(0 > x) {
return -r(-x, d)
}
r = x + 0.5*10^-d
s = scale
scale = d
r = r*10/10
scale = s
return r
}
calcscale = 30
outscale = 4
x = $3
n = $2
p = $1
x0 = x
x1 = $4
if (x1 < x)
{
x1 = x
}
s = 0
while (x <= x1) {
scale = calcscale
v = r(binprob(p, n, x), outscale)
s += v
scale = outscale
print "p = ", p/1, "\n"
print "n = ", n, "\n"
print "P(X = ", x, ") = ", v/1 , "\n"
x = x + 1
}
print "SUM (X = ", x0, "..", x1, ") = ", s/1 , "\n"
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment