my dog learned polymorphism*
The moose likes Java in General and the fly likes Standard Deviation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

Standard Deviation

Stephen Barrow
Greenhorn

Joined: Mar 03, 2004
Posts: 13
Can somebody tell me how I can change this code to allow me to hard code the values into it? such as double [] values = {10,20,30,4,2};
import java.util.*;
public class Deviator
{
public static void main(String [] args)
{

Deviator deviator = new Deviator();
List values = deviator.getValues(args);
double mean = deviator.calculateMean(values);
double stddev = deviator.calculateStandardDeviation(values);
System.out.println("values: " + values);
System.out.println("mean : " + mean);
System.out.println("stddev: " + stddev);

System.out.println("No arguments");

}
public List getValues(final String [] args)
{
List values = new ArrayList();
for (int i = 0; i < args.length; ++i)
{
try
{
Double value = Double.valueOf(args[i]);
values.add(value);
}
catch (NumberFormatException e)
{
System.err.println("Not a number: " + args[i]);
}
}
return values;
}

public double calculateMean(final List values)
{
double mean = 0.0;
int numValues = values.size();
for (int i = 0; i < numValues; ++i)
mean += ((Double)values.get(i)).doubleValue();
return mean/numValues;
}
public double calculateStandardDeviation(final List values)
{
double mean = this.calculateMean(values);
double sum = 0.0;
int numValues = values.size();
for (int i = 0; i < numValues; ++i)
{
double value = ((Double)values.get(i)).doubleValue();
double diff = value - mean;
sum += diff*diff;
}
return Math.sqrt(sum/(numValues - 1));
}
}
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11358
    
  16

There's no need to post this to multiple forums. most people just find it annoying, and it makes it harder to figure out where to post an answer.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
GeeCON Prague 2014
 
subject: Standard Deviation