1.高斯模块
import sys
import stdio
import math
def pdf(x, mu=0.0, sigma = 1.0):
x = (x - mu)/sigma
return math.exp(-x*x/2)/math.sqrt(2.0*math.pi)/sigma
def cdf(z, mu=0.0, sigma = 1.0):
z = float(z-mu)/sigma
if z < -8.0: return 0.0
if z > 8.0: return 1.0
total = 0.0
term = z
i = 3
while total != total + term:
total += term
term *= z*z/i
i += 2
return 0.5 + total * pdf(z)
def main():
z = float(sys.argv[1])
mu = float(sys.argv[2])
sigma= float(sys.argv[3])
stdio.writeln(cdf(z,mu,sigma))
if __name__ == '__main__':main()
2.随机数模块
import math
import random
import sys
import stdio
def uniformInt(lo, hi):
return random.randrange(lo, hi)
def uniformFloat(lo, hi):
return random.uniform(lo, hi)
def bernoulli(p = 0.5):
return random.random() < p
def binomial(n, p=0.5):
heads = 0
for i in range(n):
if bernoulli(p):heads += 1
return heads
def gaussian(mu=0.0, sigma=1.0):
r = 0.0
while (r>=1.0) or (r==0.0):
x = -1.0+2.0*random.random()
y = -1.0+2.0*random.random()
r = x*x+y*y
c = x*math.sqrt(-2.0*math.log(r)/r)
return c*sigma+mu
def discrete(a):
r = uniformFloat(0.0, sum(a))
subtotal = 0.0
for i in range(len(a)):
subtotal += a[i]
if subtotal > r: return i
def shuffle(a):
n = len(a)
for i in range(n):
r = random.randrange(i,n)
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
def main():
trials = int(sys.argv[1])
for i in range(trials):
stdio.writef('%2d ' , uniformInt(10,100))
stdio.writef('%8.5f ' , uniformFloat(10.0,99.0))
stdio.writef('%5s ' , bernoulli(0.5))
stdio.writef('%2d ' , binomial(100,0.5))
stdio.writef('%7.5f ' , gaussian(9.0,0.2))
stdio.writef('%1d ' , discrete([1,2,3,4]))
stdio.writeln(shuffle([2,4,8,9,3,2,1]))
#stdio.writeln()
if __name__ == '__main__': main()
3.数据分析与绘制图形模块
import math
import stdarray
import stddraw
import stdio
def mean(a):
return sum(a)/float(len(a))
def var(a):
mu = mean(a)
total = 0.0
for x in a:
total += (x-mu)*(x-mu)
return total/(len(a)-1)
def stddev(a):
return math.sqrt(var(a))
def median(a):
a = sorted(a)
#stdio.writeln(a)
if len(a)%2 == 0:
return((a[len(a)//2]+a[(len(a)//2)-1])/2.0)
else:
return( a[len(a)//2] )
def plotPoints(a):
n = len(a)
stddraw.setXscale(0,n-1)
stddraw.setPenRadius(0.005)
#stddraw.setPenRadius(1.0/(3.0*n))
for i in range(n):
stddraw.point(i,a[i])
def plotLines(a):
n = len(a)
stddraw.setXscale(0,n-1)
stddraw.setPenRadius(0.0)
for i in range(1,n):
stddraw.line(i-1,a[i-1],i,a[i])
def plotBars(a):
n = len(a)
stddraw.setXscale(0,n-1)
for i in range(n):
stddraw.filledRectangle(i-0.25,0.0,0.5,a[i])
def main():
a = stdarray.readFloat1D()
stdio.writef(' mean: %7.3f\n',mean(a))
stdio.writef('std dev: %7.3f\n',stddev(a))
stdio.writef(' median: %7.3f\n',median(a))
n = 20
a = stdarray.create1D(n,0.0)
for i in range(n):
a[i] = 1.0/(i+1)
plotPoints(a)
stddraw.show()
#plotLines(a)
#stddraw.show()
#plotBars(a)
#stddraw.show()
if __name__ == '__main__':main()