How to find out variance from array of numbers? - java

New to Java here! I have to have the user enter 10 numbers and store them in an array (of doubles). After that I need to calculate:
Mean: I have that done and I need it to get the variance & std dev requires knowing the variance.
Variance: aka the average of the squares of the distance from the mean. The part I'm confused with. For each number in the array, I have to subtract the number from the mean, square the result, and then add the square to a running total. After that I have to divide the running total by the number of values (10).
Lastly, Standard deviation: aka the square root of the variance
I have to print all the results rounded to 2 decimal places.
Example: if my dataset was just {4, 7.5, 8}, then the mean is (4 + 7.5 + 8)/3 = 19.5/3 = 6.5.
Variance = ((6.5 - 4)^2 + (6.5 - 7.5)^2 + (6.5 - 8)^2
)/3 = (6.25 + 1 + 2.25)/3 = 9.5/3 = 3.17
Standard Deviation = √3.17 = 1.78
What I need help with is the math to find out the variance. I am not sure how to take a running total or how to square root numbers in parenthesis.
public class Statistics {
public static void main(String[] args) {
int userNumbers;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the 10 numbers: ");
userNumbers = scan.nextInt();
double array[] = new double[userNumbers];
double mean;
double variance;
for (int i = 0; i < array.length; i++) {
userNumbers += userNumbers;
mean = userNumbers / 10;
}
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
System.out.print("The variance is:" + );
System.out.print("The standard deviation is: " + Math.sqrt(variance));
}
}

In this code
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
you are overwriting the value of variance in each iteration of the loop, so only the last value would be kept.
Also, for both loops, you want to use the elements in the array
Try adding to the value
for (int i = 0; i < array.length; i++) {
variance += mean - array[i];
}

Related

bad operand types for binary operator '<=' , '+='

I don't understand why my binary operands are not working for if statements. For example I get the error, bad operand types for binary operator '<='. First type: double[] Second type: double for if(prices <=5.00)
public class Prices2
{
public static void main (String[] args)
{
double[] prices = {2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05};
double average;
double total = 0.0;
int i;
for (i = 0; i < 20; i++)
{
total += prices;
}
System.out.println("Sum of all prices: "+total+"\n" );
for (i = 0; i < 20; i++)
{
if (prices <= 5.00){
System.out.println(prices + " is less than $5.00");
}
}
average = total / (20);
System.out.println("\nThe average price is " + average + "\n");
for (i = 0; i < 20; i++)
{
if (prices >= average) {
System.out.println( " Values above average: " + prices);
}
}
}
}
Since prices is an array (double[]) and 5.00 is a single double, it makes no sense to check if "prices <= 5.00". It would be like saying "If [1.2, 3.4, 5.7, 6.2, 3.4] < 5.00". So the compiler complains with that verbiage.
Updated 3/18 per follow-up question:
The short answer is to replace the prices variable with the prices[i] variable to match the iteration that checks each spot since this appears to be the goal of the computation. Also, you don't need to declare "i" at the top level. You can do that per for-loop so one loop doesn't accidentally affect another loop.
public class Prices {
public static void main(String[] args) {
// Set up a list of TEST prices to check for various conditions
double[] prices = { 2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05 };
int numberOfPrices = prices.length;
// GOAL: Calculate Sum of all numbers
// For each price (i=0, 1, 2... 19), add THAT price to the current value of total
double total = 0.0;
for (int i = 0; i < numberOfPrices; i++) {
total += prices[i];
}
System.out.println("Sum of all prices: " + total + "\n");
// GOAL: Check for for those less than 5
// For each price (i=0, 1, 2... 19), see if THAT price is less than 5.00
for (int i = 0; i < numberOfPrices; i++) {
if (prices[i] <= 5.00) {
System.out.println(prices[i] + " is less than $5.00");
}
}
// Calculate the average price (without hard-coding)
double average;
// average = total / (20);
average = total / numberOfPrices;
System.out.println("\nThe average price is " + average + "\n");
// GOAL: Check for Above Average numbers
// For each price (i=0, 1, 2... 19), see if THAT price is above the average we computed before
for (int i = 0; i < numberOfPrices; i++) {
if (prices[i] >= average) {
System.out.println(" Values above average: " + prices[i]);
}
}
}
}
prices is an array. How can Java tell what you mean by asking if 20 different doubles are less than 9? Are they all less than 9? Are they less than 9 combined? Are any of them individually less than 9?
It's not a good comparison. Your operands are bad.
You probably meant to write prices[i] instead of prices in most places

How to print out an altered dynamic array

I think I have swapped the first and last numbers of a dynamic array with each other and am at a total loss as to how to print the array with the numbers swapped.
Ideally, with the program working, the user is supposed to enter in the number of numbers they want to enter and then they will type each number in individually. Then it is supposed to output (along with standard deviation, the mean, and the original array order) the array in order, except the first number entered and the last number entered are switched. How would you go about printing the new array with the switched numbers?
Here is my code so far:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}
You can swap the integers by doing the following,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
Hope this helps :)
I did not realize that I would just have to enter another simple if statement to print it out. I was confused as to where the edited array was saving to, not realizing that it was just saving to the original array. Thank you all for the help.
In the end this is what I used for the code (in regards to my program specifically):
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}
Heres the output:
How many numbers would you like to enter? 5
Enter your numbers below:
1
2
3
4
5
The mean is: 3.0
The standard deviation is: 0.8944272
1.0, 2.0, 3.0, 4.0, 5.0
5.0, 2.0, 3.0, 4.0, 1.0

Sum and Averages of an Array

I am working on an array problem for my college course and I'm trying to find the sum and the average of an array. Here's the code I have so far.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
I know that the average works but I'm stuck on the sum. The problem I'm having is I cant seem to initialize the values in the array so that I can provide a sum for them. What am I doing wrong or what am I missing?
You have two problems in your code;
A) For-loop assignment
You don't need to make the first assignment, just adding sum to the week[index] is ok;
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
B) Calculating the average
Sum is defined as an int which is a primitive integer, because of that, the division of an integer to an integer, the output is an integer which is not precise. Output of the division (45/10) is casted to integer, then assigned to double which is rounded off to 4, then casted to double again, and '4.0' became the result.
To avoid this unprecise result, cast sum to the double as below;
average = (double)sum / weeks.length;
The corrected version of your code is as below;
Demo
public class Module55 {
public static void main(String args[]) {
// declare the array to have 10 items for 10 weeks
// also declare sum as an int and average as a double to accommodate for
// decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
// declare the array values
weeks[0] = 2;
weeks[1] = 4;
weeks[2] = 8;
weeks[3] = 10;
weeks[4] = 14;
weeks[5] = 16;
weeks[6] = 20;
weeks[7] = 22;
weeks[8] = 24;
weeks[9] = 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Output
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
And a note for scope
And one last note about the scope, check out this code;
for (int index = 0; index < weeks.length; index++)
weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
In the for-loop, because that no brackets are used, only the first statement under the for-loop will be considered in the scope of the loop by the compiler. That's why, for the next line, the compiler is giving error about the index because index is defined inside the scope of the for-loop.
you need to use brackets in your for loop. currently your code is evaluating like this:
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
you want your code to evaluate like this
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index; //logical issue, what does this line achieve?
sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
This will at least solve your procedural problems but you will still need to take a look at your logic. Try using breakpoints to debug your code.
A very simple way to achieve this in Java 8 is to use the built in mechanisms for gathering statistics:
int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());
for (int i = 0;i < weeks.length) {
sum += weeks[i];
}
System.out.println("Sum is:" + sum);
First of all, you simply don't need the line weeks[index] = index;.
And for average you have to cast the sum to double if you want to get the average in double as you have declared the sum as int.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = {2,4,8,10,14,16,20,22,24,26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
//weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
Summing an array of numbers and dividing by n to get the average like this will not get the correct value - you should not compute the average using integer division.
Also, this approach might work for the example shown, but not in general. For example, try using this code to find the average of these two value: (INT_MAX-6) and (INT_MAX-2).
The corrected code. While calculating average you have cast on of the varibale to double else you will get the average as integer
public class Mod55 {
public static void main(String args[]) {
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) {
sum += weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0) {
average = (double)sum / weeks.length;
} else {
average = 0;
}
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Java8 You could achieve the same thing like this.
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = Arrays.stream(weeks)
.sum();
double average = Arrays.stream(weeks).average().orElse(0);
you can find this handy with lambdas.The code looks something like this.
int weeks[] = {1,2,3,4};
List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
//asd.forEach(System.out::println);
//this outputs average
System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
//this outputs sum
System.out.println(asd.stream().mapToInt(val -> val).sum());
//another way to achieve this thanks to commenter
System.out.println(IntStream.of(asd).summaryStatistics());

Mean, Median, Variance calculator

I have created a program that calculates the mean, median, and variance. the program accepts up to 500 inputs. All of my methods work perfectly when there are 500 inputs (max size of my array). When there are less inputs, only the 'mean' calculator works. Here's the entire program:
public class StatsPackage{
static int i = 0, arrayLength;
static double sum = 0, mean, median, sumOfSquares, variance, stdDev;
static double calcMean (int inputs[], int count) throws IOException{
for (i = 0; i < count; i++){
sum += inputs[i];
}
mean = (sum/count);
return mean;
}
static double calcMedian (int inputs[], int count){
Arrays.sort(inputs);
if (count % 2 == 0){
median = ((inputs[(count/2)] + inputs[(count/2)- 1])/2) ;
}
if (count % 2 != 0){
median = inputs[(count-1)/2];
}
return median;
}
static double calcVariance (int inputs[], int count){
sum = 0;
for (i = 0; i < count; i++){
sumOfSquares += (inputs[i]*inputs[i]);
}
for (i = 0; i < count; i++){
sum = sum + inputs[i];
}
variance = ((sumOfSquares/count) - (sum * sum)/(count * count));
return variance;
}
static double calcStdDev (double varianceInput){
stdDev = Math.sqrt(variance);
return stdDev;
}
public static void main(String[] args) throws IOException {
NumberFormat nf = new DecimalFormat("0.##");
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String str = "test";
int inputs[] = new int [500];
int counter = 0;
int i = 0;
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(inputs, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(inputs, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(inputs, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
}
}
Here is an example output when 10 random numbers are entered:
Mean: 47.90
Median: 0.00
Variance: 0.00
Standard Deviation: 0.00
Here is the same code when 500 numbers are entered (the max size of my array):
Mean: 47.27
Median: 47.00
Variance: 856.71
Standard Deviation: 29.27
These outputs are consistent. I input 10 numbers, and I only get the mean method to work. I input 500 numbers and I get all of them working. I'm running this program against another tester program, not by inputting the numbers myself in eclipse. The tester program is my instructor's and I trust his program is working correctly.
Can anyone please help? I'm about to tear my hair out.
The problem is that you are initializing an array of size 500, but then not using all 500 indices. That means you have an array like:
[2,5,3,7,8,2,......,0,0,0,0,0,0,0,0,0,0,0,0]
So your code is going to calculate the median and std devation with all those 0s. What you should be using is an ArrayList. An ArrayList will expand in size as you add elements, whereas a regular list cannot change size.
If you cannot use an ArrayList, then you have to do a bit more work.
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
Your counter variable already has the information you need. Now, before passing this array to your mean/median/stddev methods, you need to reduce the size of the array. The easiest way to do this is to use an existing method provided to all arrays, called CopyOf() : CopyOf() method for Arrays
int[] newArray = Arrays.copyOf(inputs, counter);
Now replace your old input array with your new newArray in your method calls:
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(newArray, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(newArray, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(newArray, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
I assume you tested it with random positive integers, as it seems to be the case for these results.
When you input n (where n is small in comparison to 500) positive integers, your array is mostly full of 0's.
As Array.sort sorts the array in-place, calcMedian modifies the actual array passed, placing all these 0's to the front, and the median is, naturally, 0, as all n of them are in the back.
Then calcVariance calculates the variance of the first n 0's, as the array was sorted previously.
Finally, calcStdDev refers to the result of calcVariance.
To fix this, you should consider:
Sorting the array with this method taking a starting and ending indices.
Making a copy of the array before sorting.
Keeping the class stateless - all these methods could take anything required as arguments (while this is not strictly necessary, it will save you a lot of time in the future).
Your method of calculating variance is wrong. Have a look at the definition of the variance (for instance on wikipedia).
import java.util.Arrays;
public class StatisticalCalculations {
public static void main(String[] args) {
double[] array = { 49, 66, 73, 56, 3, 39, 33, 77, 54, 29 };
double mean = getMean(array);
double var = getVariance(array);
double med = getMedian(array);
System.out.println(Arrays.toString(array));
System.out.println("mean : " + mean);
System.out.println("variance : " + var);
System.out.println("median : " + med);
}
private static double getMean(double[] array) {
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += array[i];
return sum / l;
}
private static double getVariance(double[] array) {
double mean = getMean(array);
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += (array[i] - mean) * (array[i] - mean);
return sum / l;
}
private static double getMedian(double[] array) {
int l = array.length;
// copy array to leave original one untouched by sorting
double[] a = new double[l];
for (int i = 0; i < l; i++)
a[i] = array[i];
Arrays.sort(a);
if (l % 2 == 0)
return (a[l / 2 - 1] + a[l / 2]) / 2;
else
return a[(l - 1) / 2];
}
}
Also, you have an issue with your array, as it is fixed size versus a variable size of user inputs. Consider using ArrayList<Double> or something similar as a container for your values to avoid this problem.

Average of an array showing 1

I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;
10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant
english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;
You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;
If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.
You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.

Categories