UP | HOME

Exercise 13 solutions

Table of Contents


Python

e13.py

from numpy import array

# define the mymean() function
#
def mymean(x):
    n = len(x)
    m = 0
    for i in range(n):
        m = m + x[i]
    m = m / n
    return m

# define the mystd() function
#
def mystd(x):
    n = len(x)
    s = 0
    xm = mymean(x)
    for i in range(n):
        s = s + ((x[i]-xm)**2)
    s = s / (n-1)
    return s

# test the function
#
a = array([1,2,3,4,5], "float")
a_s = mystd(a)
print str(a_s)

MATLAB / Octave

mymean.m

function m = mymean(x)
  n = length(x);
  m = 0;
  for i = 1:n
    m = m + x(i);
  end
  m = m / n;

mystd.m

function s = mystd(x)
  n = length(x);
  xm = mymean(x);
  s = 0;
  for i = 1:n
    s = s + (x(i)-xm)^2;
  end
  s = s / (n-1);

e13.m

a = [1,2,3,4,5];
a_s = mystd(a);
disp(num2str(a_s));

R

e13.R

# define the mymean() function
#
mymean <- function(x) {
    n <- length(x)
    m <- 0
    for (i in seq(n)) {
	m <- m + x[i]
    }
    m <- m / n
    m
}

# define the mystd() function
#
mystd <- function(x) {
    n <- length(x)
    s <- 0
    xm <- mymean(x)
    for (i in seq(n)) {
	s <- s + ((x[i]-xm)**2)
    }
    s = s / (n-1)
    s
}

# test the function
#
a <- c(1,2,3,4,5)
asd <- mystd(a)
cat(asd,"\n")

C

e13.c

// compile with: gcc -o e13 e13.c

#include <stdio.h>
#include <stdlib.h> // for malloc

double mymean(double x[], int xlen) {
  double out = 0;
  int i;
  for (i=0; i<xlen; i++) {
    out += x[i];
  }
  out = out / xlen;
  return out;
}

double mystd(double x[], int xlen) {
  double s = 0;
  int i;
  double xm = mymean(x, xlen);
  for (i=0; i<xlen; i++) {
    s += (x[i]-xm) * (x[i]-xm);
  }
  s = s / (xlen-1);
  return s;
}

int main(int argc, char const *argv[])
{
  double x[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
  int xlen = 5;
  double xs = mystd(x, xlen);
  printf("the std of x is %.3f\n", xs);

  return 0;
}

Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License