+ indep. WoS citations

Python and Networks - Homework - 2016-02-09

Problem: Plot the relative standard deviation, \(\sigma/E\), of \(N = 10, 100, \ldots, 10^5\) random numbers (same interval, uniform distribution) as a function of \(N\). Which simple type of \(f(N)\) function could describe the convergence of \(\sigma/E\) to its expectation value?

Solutions:

1.  FIJ

1.1  Relative standard deviation in the \(N\to\infty\) limit

The mean is \(E=1/2\). The standard deviation is \(\sigma=\sqrt{\int_0^1(x-E)^2dx}=\sqrt{\int_0^1(x^2-x+1/4)dx}=1/\sqrt{12}\). Thus, in the \(N\to\infty\) limit we have \(\sigma/ E = 1/\sqrt{3}\approx 0.577\).

1.2  Code (randconv.py)

import random

# --- function definitions ---

# relative standard deviation of N random numbers in [0,1)
def print_avg_stdDev(n):
    # initialize sum and sum of squares
    sum = 0; sumSqr = 0;
    for i in range(n):
        # add random number and its square to the sum and the sum of squares
        num = random.random(); sum += num; sumSqr += num * num
    # compute and print average and std.dev. and relative std.dev.
    avg = sum/n; stdDev = ( sumSqr/n - avg * avg ) ** .5
    # expected value of relative std.dev: ( 1 / [ 2 sqrt(3) ] ) / (1/2) = 1 / sqrt(3)
    print "%d\t%.5g\t%.5g\t%.5g\t%.5g" % ( n, avg, stdDev, stdDev/avg, 3**(-.5) )

# --- main ---

# print header
print "# N\n#\tAverage\n#\t\tStandard deviation\n#\t\t\tRelative stdDev"
print "#\t\t\t\tExpected value of rel.stdDev\n"

# print output for many sample sizes
for j in range(1,7):
    print_avg_stdDev( 10**j )

1.3  How to use the python code

python randconv.py > randconv.txt

1.4  Output (example, randconv.txt)

# N
#       Average
#               Standard deviation
#                       Relative stdDev
#                               Expected value of rel.stdDev

10      0.48823 0.31177 0.63857 0.57735
100     0.47671 0.28735 0.60278 0.57735
1000    0.49278 0.2947  0.59804 0.57735
10000   0.49406 0.28868 0.5843  0.57735
100000  0.49785 0.28892 0.58034 0.57735
1000000 0.49995 0.28833 0.57673 0.57735

1.5  Gnuplot command file (randconv.gnu)

# settings
se term posts lands color enh dash "Helvetica" 22
se log xy
se xlab 'N: Number of random numbers from the [0,1) interval'
se ylab "Absolute value of\nrelative std.dev. minus its expected value"
se grid
se o 'randconv.ps'
se xtic ("10" 10, "10^{&{.}3}" 1000, 0.001, "10^{&{.}5}" 1e+5)
se ytic ("10^{{/Symbol \055}&{.}1}" 0.1, "10^{{/Symbol \055}&{.}2}" 0.01, \
         "10^{{/Symbol \055}&{.}3}" 0.001, "10^{{/Symbol \055}&{.}4}" 0.0001)

# plotting
p [5:2e+6][5e-5:1e-1] \
\
'randconv.txt' \
\
u 1:(abs($4-$5)) \
\
w p pt 2 ps 2.5 lt 1 lw 4 \
\
noti

1.6  Use gnuplot and convert the image

gnuplot randconv.gnu
convert -geometry 320 -rotate 90 -flatten randconv.ps randconv.png

1.7  Output (randconv.png)

This is similar to a line on a log-log plot. In other words, it is similar to a power-law.

2.  SZE

2.1  Python code

import random # import the package

f=open('homework1.txt','w') # open the file 

print >>f, "Number\tAvg\tSigma"  # write to file

for n in (10,100,1000,10000,100000): # cycle on list between ()
    sum=0; sumSqr=0

    for i in (range(n)): # range(n) -> list from 0 to (n-1)
        r=random.random() # package.name
        sum+=r # increase with r
        sumSqr+=r**2

    avg=sum/n
    sigma=(sumSqr/n-avg**2)**.5
    print >>f, "%d\t%g\t%g" % (n, avg, sigma)

2.2  Output

3.  BGS

3.1  Python code

import random

m=open("atlag.dat", "w+")
m.write("#n\tmean\tsd\n")

for n in(10,100,1000,10000):     

    summ=0
    sumSqr=0 
    for i in(range(n)): 
        r=random.random()
        summ+=r 
        sumSqr+=r*r 
        avg=summ/n 
        sigma=(sumSqr/n-avg*avg)**0.5 
    m.write( "%d\t%g\t%g\n" % (n,avg,sigma))
    print "%d\t%g\t%g\n" % (n,avg,sigma)

3.2  Output

4.  SZT

4.1  Python code

# Python programming and networks - Homework 1
# Szorenyi Tamas
# Note that I learned the python basics all by myself from the internet,
# for I could not attend the first class, so this might not be the most elegant solution.
#
# Relative standard deviation of 10, 100, 1000, 10000, 100000 random numbers.
# Calculation plan:
#       1) Generating random numbers
#       2) Calculating mean value (average)
#       3) Calculating standard deviation
#       4) Rel. st. dev. = St. dev. / Avg.

# Getting necessary standard libraries
import random
import math

# Set range of random numbers (the actual limits don't matter)
LowerLimit = 0.0
UpperLimit = 1000.0

# def RelativeStandardDeviation (HowManyNumbers, RelStdDev):    -> seems like a dead end, could not use it well

print "Relative standard deviation of N random numbers:"

for l in range(5):
        N = 10**(l+1)
        # Generating N random numbers
        RandomNumbers = [random.uniform(LowerLimit, UpperLimit) for i in range(N)]
        # Calculating mean value (average)
        Mean = 0.0
        for j in range(N):
                Mean += RandomNumbers[j]
        Mean = Mean / N
        # Calculating standard deviation
        StdDev = 0.0
        for k in range(N):
                StdDev += math.pow((RandomNumbers[k] - Mean), 2)
        StdDev = math.sqrt(StdDev / N)
        # Relative standard deviation
        RelStdDev = StdDev / Mean

        print "N = %d \t RSD = %.4f" % (N, RelStdDev)

4.2  Output

5.  GD

5.1  Python code

# Prints out the average and sigma
# of n randomly generated numbers between 0 and 1

import random

# Prints header
print "#n\taverage\tsigma\tsigma/avg"

# Take each N value: N = 10, 100, 1000, 10000, 100000, 1000000
for n in (10, 100, 1000, 10000, 100000, 1000000):
        # Sum of the generated numbers
        sum = 0
        # Sum of the square of the generated numbers
        sumsqr = 0

        for i in range(n):
                r = random.random()
                sum += r
                sumsqr += r * r
        # Average of the generated numbers
        avg = sum / n
        # Sigma of the generated numbers
        sigma = (sumsqr / n - avg * avg) ** 0.5

        # Print out the average and sigma of the generated numbers
        print "%d\t%g\t%g\t%g" % (n, avg, sigma, sigma/avg)

5.2  Output

Please note that symbols should have linewidth \(\ge\) 2. Otherwise they are not visible.

6.  JM

6.1  Python code

import random
import math

# create lists of random doubles (uniform, between 0 and 1) for N=10, 100, ... 10E8  
# and print the relative deviance of these numbers
for i in range(1, 9):

    N = int(math.pow(10, i))

    # generating a list of random numbers with the default random class
    listOfRandomNumbers = [random.random() for i in range(0, N)]

    # the expected value of these numbers is their sum / N, 
    # the same logic applies to their squeres as well
    E = sum(listOfRandomNumbers) / N
    ESqr = sum( i*i for i in listOfRandomNumbers) / N

    # the relative standard deviation of the generated random numbers is 
    # sigma/E = sqrt[E(X^2) - E^2(X)] / E(X) = sqrt[E(X^2) / E^2(X) -1 ] = sqrt[]
    relativeStandardDeviation = math.sqrt(ESqr / (E * E)  - 1)

    print N, relativeStandardDeviation, math.fabs(relativeStandardDeviation - 1/math.sqrt(3))

6.2  Output

In the gnuplot command file the   {/Sigma S}   part in the ylabel should be replaced with   {/Symbol s}   .

7.  KZS

7.1  Python code

#-*- coding: utf-8 -*-
import random as rnd
import numpy as np

#print(rnd.random())

print("#N \t atlag \t szoras \t relativ_szoras")
for n in np.logspace(1.0, 5.0, num=10): # 10, 100 1000, 10 000 100 000 véletlen számot fogunk generálni, ezt mértani sorozattal oldottam meg
  n = int(n)
  sum = 0
  sumOfSquares = 0 #pythonban, mint C-ben, a változó definiálásánál kell neki adni egy nulla értéket!! (perlben nem kellett)
  for i in range(n):
    r = rnd.random()
    sum += r
    sumOfSquares += r * r

  average = sum/n
  sigma = (sumOfSquares/n - average*average)**0.5  #kiszámolom az átlagot és a szórást az n db szám összegéből és négyzetösszegéből

  print "%d \t %8g \t %8g \t %8g" % (n,average,sigma,(sigma/average))

7.2  Output

8.  BB

8.1  Python code

import random # random.random()

# file for storing the needed values
f = open("C:/FizikaMsc/pythonHalozatok/hf1/relatSTD-n.txt", "w")

# print header
f.write("n\tavg\tsigma\trelatSTD\texpValue\n")

#Looping through the N values, and calculating the sum and the standard deviation for every generated n number
for n in (10, 100, 1000, 10000, 100000):
    # initailizing the sum and sum of squares
    sum = 0
    sumSqr = 0
    for i in (range(n)):
        # calculate the sum and sum of squares
        r = random.random()
        sum += r
        sumSqr += r*r

    avg  = sum/n
    sigma = (sumSqr/n - avg*avg)**0.5

    # save values into a file
    f.write("%d\t%g\t%g\t%g\t%g\n" % (n, avg, sigma, sigma/avg, 3**(-0.5)))
    #print   "%d\t%g\t%g\t%g\t%g" % (n, avg, sigma, sigma/avg, 3**(-0.5))

f.close()

8.2  Output