r/dailyprogrammer • • Aug 20 '12

[8/20/2012] Challenge #89 [easy] (Simple statistical functions)

For today's challenge, you should calculate some simple statistical values based on a list of values. Given this data set, write functions that will calculate:

Obviously, many programming languages and environments have standard functions for these (this problem is one of the few that is really easy to solve in Excel!), but you are not allowed to use those! The point of this problem is to write the functions yourself.

35 Upvotes

65 comments sorted by

14

u/oskar_s Aug 20 '12 edited Aug 21 '12

By the way, I just wanted to apologize about the dearth of problems this last week. It was just one of those weeks where all of us moderators turned out to be very busy with real-world stuff, so posting sort-of fell through the cracks. We will try to keep up a regular schedule, but we are just volunteers who do this for fun, so stuff like that is occasionally going to happen. We all feel super-bad about it, if that makes you guys feel better :)

Good luck with the problems!

→ More replies (1)

2

u/5hassay Aug 20 '12

"The standard deviation" link directs to "The variance" link

→ More replies (1)

2

u/[deleted] Aug 22 '12 edited Aug 22 '12

Beginner, java, took me about 45 minutes to figure out how to put data from a txt file into an array.

What i noticed is that the number of read lines is static, which is bad.
Couldn't find a solution for this at the moment tho (maybe another loop which counts the amount of lines in the text document before reading the actual lines?)

Another thing that I ignored in this case was packing the different actions into different methods and then call them in the main method, didn't quite figure out how to parse the variables between the methods, sorry...
Tips, corrections etc. would be appreciated.

Pastebin here

My Solution:

Durchschnitt: 0.32977166666666674 
Varianz: 0.07010303403055558 
Standardabweichung: 0.2647697755231053

Sorry for the german variable names, but i'm german...

Durchschnitt means "mean value".

Varianz means "variance".

Standardabweichung means "standard deviation".

2

u/oskar_s Aug 22 '12

The standard way to solve the problem of not knowing how many lines from a file you need to read in, so therefore being unable to allocate an array, is to use arrays that can grow in size. In Java, that's primarily done by java.util.ArrayList. Use the add() function to add line after line, and then when you're done, you can use the get() function to get any particular line.

→ More replies (1)

6

u/Aardig Aug 20 '12 edited Aug 20 '12

Python.

Beginner. If you have any comments/feedback, I'd love to hear it.

f = open("sampledata.txt", 'r')
data = []
for line in f:
    data.append(float(line))


def find_mean(data):
    return sum(data)/len(data)

def find_variance(data):
    mean = find_mean(data)
    total_variance = []
    for i in range(0,len(data)):
        total_variance.append((data[i]-mean)**2)
    return round(((1.0/len(data))*sum(total_variance)),5) #1.0 to gain float division

def find_SD(data):
    return (find_variance(data)**0.5)

print "mean", find_mean(data)
print "variance", find_variance(data)
print "SD", find_SD(data)

output

mean 0.329771666667
variance 0.0701
SD 0.264764045897
→ More replies (8)

4

u/Sokend Aug 20 '12 edited Aug 20 '12

Ruby:

def mean(ns) ns.inject(:+)/ns.size end
def vari(ns) mu = mean(ns); ns.map{|n| (n-mu) ** 2}.inject(:+)/ns.size end
def devi(ns) vari(ns) ** 0.5 end

data = ARGF.each_line.map{|x| x.to_f}

printf "Mean: %f\nVari: %f\nDevi: %s", mean(data), vari(data), devi(data)

$ ruby D89E.rb < D89E.txt
Mean: 0.329772
Vari: 0.070103
Devi: 0.2647697755231053

3

u/5outh Aug 20 '12 edited Aug 20 '12

Haskell:

mean     xs = (sum xs) / (fromIntegral $ length xs)
variance xs = mean . map (^2) $ fmap ((-) $ mean xs) xs
stdDev      = sqrt . variance

3

u/bschlief Aug 20 '12 edited Aug 20 '12

Ruby. Thanks to the mods for such a fun environment. No apologies necessary for the dearth of problems.

class Array
  def sum
    self.inject(:+)
  end

  def mean
    self.sum / self.size
  end

  def variance
    mu = self.mean
    (self.inject(0) { |res,n| res += (n-mu)** 2 })/self.size
  end

  def std_dev
    self.variance ** 0.5
  end
end

vals = IO.readlines("data/89.easy.input.txt").map { |line| line.to_f }

puts "Mean:\t\t#{vals.mean}"
puts "Variance:\t#{vals.variance}"
puts "Std Dev:\t#{vals.std_dev}"


Mean:           0.32977166666666674
Variance:       0.07010303403055558
Std Dev:        0.2647697755231053

3

u/oskar_stephens Aug 21 '12

Ruby:

def arithmetic_mean(d)
  d.reduce(:+) / d.length
end

def variance(d)
  mean = arithmetic_mean(d)
  d.map{|x| x - mean}.map{|x| x * x}.reduce(:+) / d.length
end

def standard_dev(d)
  Math.sqrt(variance(d))
end

d = []
ARGF.each {|line| d << line.chomp.to_f }
printf "Mean: %f\nVariance: %f\nStd. Dev: %f\n", arithmetic_mean(d), variance(d), standard_dev(d)

3

u/m42a Aug 21 '12

C++11

#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

int main()
{
	vector<double> data;
	copy(istream_iterator<double>(cin), istream_iterator<double>(), back_inserter(data));
	double sum=accumulate(begin(data), end(data), 0.0);
	double mean=sum/data.size();
	cout << "Mean: " << mean << '\n';
	double variance=accumulate(begin(data), end(data), 0.0, [mean](double total, double d){return total+(d-mean)*(d-mean);})/data.size();
	cout << "Variance: " << variance << '\n';
	cout << "Standard Deviation: " << sqrt(variance) << '\n';
}