So I have an assignment where i'm supposed to create a program that generates 100 random integers and stores them in a single dimensional array. I am then supposed to calculate the average, standard deviation and variance. Through a lot of trial and error I was able to make a program that did this but what I missed was that it said to write a separate method for each property(average, standard deviation and variance). How would i go about doing that?
package homeassignment5;
public class HomeAssignment5 {
public static void main(String[] args) {
int n;
n = 100;
int[] random = new int [n];
for (int i = 0; i<random.length; i++)
random[i] = (int) (Math.random()* n);
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
//System.out.println("Total is: " + total);
System.out.println("Average is: " + average);
System.out.println("Variance is " + var);
System.out.println("Standard deviation is " + sd);
/*for (int i = 0; i<random.length; i++)
System.out.println(random[i]);
*/
}
}
Might be a bit of a mess but i'm really new to java and this was the product of a ton of trial and error.
So there are several ways of going about this, but the easiest would probably be this:
public class HomeAssignment5 {
private static int[] random;
public static void main(String[] args){
random = = new int[100];
...
}
public static void getAverage(){
// void if you want to print it here, double if you want to print in main
double average = 0;
int total = 0;
for(int i = 0; i < 100; i += 1)
total += random[i];
average = total / n; // you'll want to do this outside of the loop to
// to get the correct result!
System.out.println("Average: " + average);
}
...
}
You could alternatively pass the array to each method as a parameter.
By the way, in what you posted here, you still haven't actually written any random numbers into the array, so remember to do that, it's currently still all zero.
I believe this should help you..
All the functionalities are separated in form of methods,
the initialization is separated.
** WELCOME TO REFACTORING **
public class Refactor {
private int[] random;
private int n;
private double total = 0;
private double average = 0;
private double variance = 0;
private double sd = 0;
public Refactor(int n) {
this.n = n;
this.populateArray();
}
private void populateArray() {
random = new int[n];
for (int i = 0; i < random.length; i++)
random[i] = (int) (Math.random() * n);
}
public double getAverage() {
average = 0;
total = 0;
for (int element : random) {
total += element;
}
average = total / n;
return average;
}
public double getVariance() {
variance = 0;
for (int i = 0; i < random.length; i++) {
variance += (random[i] - average) * (random[i] - average);
}
variance = variance / random.length;
return variance;
}
public double getSD() {
this.getVariance();
sd = 0;
sd = Math.sqrt(variance);
return sd;
}
public static void main(String[] args) {
Refactor ref = new Refactor(100);
System.out.println("Average is: " + ref.getAverage());
System.out.println("Variance is " + ref.getVariance());
System.out.println("Standard deviation is " + ref.getSD());
}
}
How would i go about passing the array to each method?
The first and most straightforward of the three methods is average:
static double average(int [] r)
{ double total = 0;
for (int e: r) total += e;
return total/r.length;
}
For the second method, the standard deviation, I recommend not to pass the array, but rather the variance, since if the program has calculated the variance anyway, it need not be recalculated, and if it doesn't have, the SD method can be called with a call to the variance method as its argument.
static double SD(double variance) { return Math.sqrt(variance); }
For the third method, the variance, I recommend not only to pass the array, but also its average, with similar reasoning as above.
static double variance(int [] r, double average)
{ double var = 0;
for (int e: r) var += (e - average) * (e - average);
return var/r.length;
}
With those three methods defined, you can now replace
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
with
double average = average(random);
double var = variance(random, average);
double sd = SD(var);
Related
I have a text file with data that looks like this (TestData.txt):
Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
Richard Perez|100|84|73|81|92|84|95|96|95|100
Ivan Dyer|77|91|90|75|97|94|76|89|90|92
Craig Palmer|91|84|98|89|82|75|78|96|100|97
Madeline Rogers|75|79|78|93|91|76|80|88|100|81
Chelsea Roxas|87|94|89|96|95|85|88|92|86|86
Jasper Bautista|100|83|93|100|98|97|96|97|97|98
Tyler Perez|82|89|90|78|89|96|75|88|90|96
My code parses the file and does some calculations with it.
However, in the method arrangeList() within which calls another method called getTestAvg() (calculates column means), the program ignores Tyler Perez's scores.
I noticed that the results I am getting were inaccurate so I went and printed the whole 2d array with all the test scores and the last column is nowhere to be found.
My entire code is below and I hope someone could point out what causes this.
I keep getting an IndexOutOfBounds error whenever I try to switch N (# of students) and M (# of tests) to see what happens. At first, I have 10 students and 10 tests, and all the calculations were correct, but when I added another student, the calculations became inaccurate.
I apologize in advance if my code isn't as well-designed as I'm not an experienced programmer.
import java.util.*;
import java.io.*;
public class TestAverages
{
private static int[] grades;
private static int[] testTotal;
private static int N;
private static double classTotal;
private static int M;
public static void main(String[] args) throws FileNotFoundException
{
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException
{
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
int index = 0;
while(in.hasNextLine())
{
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
N = grades.length;
for(int i = 0; i < N; i++){
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double)grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
M++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades)
{
double total = 0.0;
double avg = 0.0;
int N = grades.length;
for(int i = 0; i < N; i++){
total += grades[i];}
avg = total / N;
return avg;
}
public double getClassAvg(double total)
{
double classAvg = total / M;
return classAvg;
}
public double[][] arrangeList(ArrayList testScores)
{
double[][] tests = new double[N][N];
int len = tests.length;
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
for(int i = 0; i < len; i++)
{
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index)
{
double testAvg = 0.0;
for(int i = 0; i < N; i++)
{
testAvg += testScores[i][index];
}
return testAvg / N;
}
}
Here are the numbers I'm supposed to be getting (top) compared to what my program outputs (bottom).
As the other responses already stated, you had quite the issue with your variables and loops. I now changed N to # of students and M to # of tests to be as you stated in your question.
Next time, maybe try to improve your variable naming, so you don't get confused. (e.g. switch out n and m for s (students) and t (tests), if you like your variable names short).
This should work now. Just check against your code to see the changes.
import java.util.*;
import java.io.*;
public class TestAverages {
private static int[] grades;
private static int n = 0; // amount of students
private static int m; // amount of tests
public static void main(String[] args) throws FileNotFoundException {
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException {
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
while (in.hasNextLine()) {
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
m = grades.length;
for (int i = 0; i < m; i++) {
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double) grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
n++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades) {
double total = 0.0;
double avg = 0.0;
for (int i = 0; i < grades.length; i++) {
total += grades[i];
}
avg = total / grades.length;
return avg;
}
public double getClassAvg(double total) {
double classAvg = total / n;
return classAvg;
}
public double[][] arrangeList(ArrayList<Double> testScores) {
double[][] tests = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tests[i][j] = (Double) testScores.get(i * m + j);
}
}
for (int i = 0; i < m; i++) {
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index) {
double testAvg = 0.0;
for (int i = 0; i < n; i++) {
testAvg += testScores[i][index];
}
return testAvg / n;
}
}
You need to account for the different sizes. I think you want primarily the number of TESTS (not students), but you can't just use len for both index bounds.
double[][] tests = new double[N][M];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
Note that it didn't just resize the array, but it changed the loop conditions to loop the proper amount for inner and outer loop.
In the line
double[][] tests = new double[N][N];
of function arrangeList
you make your test array as N X N.
I believe youh should do something like
double[][] tests = new double[M][N];
It's just a suggestion as in your code it seems M = number of students and N = number of tests, differently from what you write in your question.
In general you should review all the method arrangeList and probably getTestAvg too (loop on N, instead of M), as the loops on variable len are intended for a N X N array, which is not the case.
I am trying to resolve an issue for this assignment I was given for Homework. I am currently stuck and would appreciate any help that could guide me in correcting the program.
The original assignment is as follows:
Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. Write two methods : one to calculate and return the average high and one to calculate and return the average low of the year. Your program should output all the values in the array and then output the average high and the average low.
This is the code I have assembled so far and have an error that I am not able to resolve. It is " incompatible types: converting double[][] cannot be converted to double. The lines in question are Line 8, and Line 110 ( the last return in the program).
import java.util.*;
public class Weather
{
public static void main(String[] args)
{
double[][] tempData = getData();
printTempData(tempData);
double avgHigh = averageHigh(tempData);
double avgLow = averageLow(tempData);
int indexHigh = indexHighTemp(tempData);
int indexLow= indexLowTemp(tempData);
System.out.format("The average high temperature is %4.1f%n", avgHigh);
System.out.format("The average low temperature is %4.1f%n", avgLow);
System.out.format("The index of high temperature is %2d%n", indexHigh);
System.out.format("The index of low temperature is %2d%n", indexLow);
}
private static void printTempData(double[][] tempData)
{
System.out.format("%6s:%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%n","Month","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
System.out.format("%6s:","Low");
for (int i = 0; i < tempData[0].length;i++)
{
System.out.format("%4.1s", tempData[0][i]);
}
System.out.format("%n");
System.out.format("%6s: ","High");
for (int i = 0; i < tempData[1].length; i++)
{
System.out.format("%4.1f", tempData[1][i]);
}
System.out.format("%n");
}
private static int indexLowTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[0][0];
for (int i = 0; i < tempData[0].length; i++)
{
if (temp > tempData[0][i])
{
temp = tempData[0][i];
index = i;
}
}
return index +1;
}
private static int indexHighTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[1][0];
for(int i = 0; i< tempData[1].length; i++)
{
if ( temp < tempData[1][i])
{
temp = tempData[1][i];
index = i;
}
}
return index + 1;
}
private static double averageHigh(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i < tempData[0].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double averageLow(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i > tempData[1].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double getData()
{
double[][] tempData = new double[2][12];
Random r = new Random();
for (int j = 0; j < tempData[0].length; j++)
{
tempData[0][j] = 30 + Math.sqrt(j) - r.nextDouble();
tempData[1][j] = 30 + Math.sqrt(j) + r.nextDouble();
}
return tempData;
}
}
Your method private static double getData() should be private static double[][] getData()
You already declared an array
double[][] tempData = getData();
but you are trying to call
private static double getData()
thus the error "converting double[][] cannot be converted to double."
Hence change to
private static double[][] getData()
The method should be private static double[][] getData()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This code is supposed to find the Standard deviation of an random integers in an ArrayList. However, my code for the Standard deviation doesn't show the right outcome. It shows another number then expected.
What am I doing wrong?
import java.io.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args)
{
ArrayList<Integer> values = new ArrayList<Integer>();
int count = 0;
int total = 0;
Random r = new Random();
for (int i = 1; i <= 10; i++) {
values.add(r.nextInt(90)+ 1);
System.out.println(values);
}
System.out.println(mean(values));
System.out.println(sd(values));
}
public static double mean (ArrayList<Integer> table)
{
int total = 0;
for ( int i= 0;i < table.size(); i++)
{
int currentNum = table.get(i);
total+= currentNum;
}
return total/table.size();
}
public static double sd (ArrayList<Integer> table)
{
double mean= mean(table);
double temp =0;
for ( int i= 0; i <table.size(); i++)
{
temp= Math.pow(i-mean, 2);
}
return Math.sqrt(mean( table));
}
public static void selectionSort(ArrayList<Integer> table)
{
int count = table.size();
for(int pos = 0; pos < count - 1; pos++)
{
int locMin = pos;
for(int i = pos + 1; i < count; i++)
{
if(table.get(i) < table.get(locMin))
locMin = i;
}
int temp = table.get(pos);
table.set(pos, table.get(locMin) );
table.set(locMin, temp);
}
}
}
Your standard deviation calculation has errors:
This is the algorithm for finding the standard deviation:
Step 1: Find the mean.
Step 2: For each data point, find the square of its distance to the mean.
Step 3: Sum the values from Step 2.
Step 4: Divide by the number of data points.
Step 5: Take the square root.
Therefore, your code should look like:
public static double sd (ArrayList<Integer> table)
{
// Step 1:
double mean = mean(table);
double temp = 0;
for (int i = 0; i < table.size(); i++)
{
int val = table.get(i);
// Step 2:
double squrDiffToMean = Math.pow(val - mean, 2);
// Step 3:
temp += squrDiffToMean;
}
// Step 4:
double meanOfDiffs = (double) temp / (double) (table.size());
// Step 5:
return Math.sqrt(meanOfDiffs);
}
Note: Your mean calculation has a loss of precision.
You have:
return total/table.size();
It should be:
return (double) total / (double) table.size();
Here is a sample Standard Deviation Program:
// Beginning of class Deviation
public class Deviation
{
// Beginning of method main
public static void main(String[] args)
{
// Declare and create an array for 10 numbers
double[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Print numbers
printArray(numbers);
// Display mean and deviation
System.out.println("The mean is " + findMean(numbers));
System.out.println("The standard deviation is " +
findDeviation(numbers));
} // End of main
/* Method for computing deviation of double values */
// Beginning of double findDeviation(double[])
public static double findDeviation(double[] nums)
{
double mean = findMean(nums);
double squareSum = 0;
for (int i = 0; i < nums.length; i++)
{
squareSum += Math.pow(nums[i] - mean, 2);
}
return Math.sqrt((squareSum) / (nums.length - 1));
} // End of double findDeviation(double[])
/* Method for computing deviation of int values */
// Beginning of double findDeviation(int[])
public static double findDeviation(int[] nums)
{
double mean = findMean(nums);
double squareSum = 0;
for (int i = 0; i < nums.length; i++)
{
squareSum += Math.pow(nums[i] - mean, 2);
}
return Math.sqrt((squareSum) / (nums.length - 1));
} // End of double findDeviation(int[])
/** Method for computing mean of an array of double values */
// Beginning of double findMean(double[])
public static double findMean(double[] nums)
{
double sum = 0;
for (int i = 0; i < nums.length; i++)
{
sum += nums[i];
}
return sum / nums.length;
} // End of double getMean(double[])
/** Method for computing mean of an array of int values */
// Beginning of double findMean(int[])
public static double findMean(int[] nums)
{
double sum = 0;
for (int i = 0; i < nums.length; i++)
{
sum += nums[i];
}
return sum / nums.length;
} // End of double getMean(int[])
/* Method for printing array */
// Beginning of void printArray(double[])
public static void printArray(double[] nums)
{
for (int i = 0; i < nums.length; i++)
{
System.out.print(nums[i] + " ");
}
System.out.println();
} // End of void printArray(double[])
} // End of class Deviation
I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.