Saturday, January 31, 2015

R2. Normal Distribution in R


The R function rnorm gives samples according to Normal Distribution

# ex2.R
sig <- rnorm(10000)
num_pos <- sig>=0
a <- sum(num_pos)/length(num_pos)*100
print(sprintf('The percentage of positive numbers in sig is %.2f.',
              a))
print(sprintf('sig has %.5f mean.',mean(sig)))
print(sprintf('sig has %.5f std away from 1',abs(sd(sig)-1)))
hist(sig,breaks = 45, xlab ='x', ylab ='Frequency',
     main = 'Normal Distribution',col = 'gray')
## [1] "The percentage of positive numbers in sig is 50.26."
## [1] "sig has 0.00961 mean."
## [1] "sig has 0.00734 std away from 1"

Output:

 


py2. Normal Distribution in Python

We can get samples based on the normal distribution from numpy.random.normal:

# ex2.py
from __future__ import division, print_function
from numpy.random import normal
import matplotlib.pyplot as plt
sig = normal(size = 10000)
num_pos = sig>=0
a = sum(num_pos)/len(num_pos)*100 
print('The percentage of positive numbers in sig is %.2f.' % a)
print('sig has %.5f mean.' % sig.mean())
print('sig has %.5f std away from 1' % abs(sig.std()-1))
plt.hist(sig,bins=45,color='gray')
plt.title('Normal Distribution')
plt.xlabel('x')
plt.ylabel('Frequency')
plt.show()
## The percentage of positive numbers in sig is 49.40.
## sig has -0.00742 mean.
## sig has 0.00592 std away from 1

Output

R1. The choose function in R

The choose function finds out how many combinations we have of k elements, from a total of n elements.


For example for {1,2,3}, we have 3 combinations {1,2},{1,3},{2,3}


For combinations, we have to remember order is not important.

# ex1a.R
a <- choose(k=2,n=3)
b <- choose(3,2)
c <- choose(2,n=3)
print(a)
print(b)
print(c)

We may write a function using the factorial definition

# ex1b.R
choose1 <- function(n,k) {
  factorial(n)/factorial(k)/factorial(n-k)
}
a <- choose1(k=2,n=3)
b <- choose1(3,2)
c <- choose1(2,n=3)
print(a)
print(b)
print(c)

py1. Creating combinations in Python

We can use combinations function from itertools module to create combinations:

#ex1a.py
from itertools import combinations

A = [1,2,3]

B = list(combinations(A,2))

print 'The list is ', B, ' with a length of ', len(B)

## The list is  [(1, 2), (1, 3), (2, 3)]  with a length of  3

We can also create a function using the factorials function

# ex1b.py
from math import factorial
def choose1(n,k):
    return factorial(n)/factorial(k)/factorial(n-k)
print choose1(n=3,k=2)
print choose1(3,2)
## 3
## 3