Variance with an array of doubles - java

I am tasked to create a program where i am supposed to to store the 10 numbers in an array of doubles. Then i have to calculate mean, variance, and standard deviation.
Everything works fine besides the variance and, in turn, the standard deviation (i believe the code works for Std Dev).
I have put copied a sample output and a desired output for your convenience.
Thank you!
package Statistics;
import java.util.Scanner;
public class Statistics {
public static void main(String[] args) {
double values[] = new double[10];
//Declaring variables
double sum1 = 0.0, mean;
double variance, sum = 0.0;
Scanner scanner = new Scanner(System.in); //scanner to allow user to input
System.out.print("Enter the 10 numbers: ");
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextDouble();
}
for (int i = 0; i < values.length; i++)
{
sum1 += values[i];
}
mean = sum1 / values.length;
for (int i = 0; i < values.length; i++)
{
sum += Math.pow(values[i] - mean, 2);
}
variance = sum / (values.length - 1);
double standardDeviation = Math.sqrt(variance);
System.out.printf("\nMean : %.1f", mean); //calculate mean
System.out.printf("\nVariance : %.2f", variance); //calculate variance
System.out.printf("\nStandard Deviation : %.2f", standardDeviation); //calculate StdDev
scanner.close(); //close the scanner
}
}
Desired Output:
Enter the 10 numbers: 5
8
10
6
12
3
5
7
9
-2
Mean : 6.3
Variance : 14.01
Standard Deviation : 3.74
Sample output:
Enter the 10 numbers: 5
8
10
6
12
3
5
7
9
-2
Mean : 6.3
Variance : 15.57
Standard Deviation : 3.95

You're using the wrong formula for variance. Instead of variance = sum / (values.length - 1); try variance = sum / values.length; and you should get:
Mean : 6.3
Variance : 14.01
Standard Deviation : 3.74

The variance formula is sum / the length of values. Your std depends on the variance for the correct answer. Hence, why both are incorrect. If space isn't a concern - try doing each step a line at a time, then combine them to once it is working.

Related

5.16 LAB: Adjust list by normalizing _ zybook - Java

5.16 LAB: Adjust list by normalizing
When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This adjustment can be done by normalizing to values between 0 and 1, or throwing away outliers.
For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow. Assume that the list will always contain fewer than 20 floating-point values.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Ex: If the input is:
5 30.0 50.0 10.0 100.0 65.0
the output is:
0.30 0.50 0.10 1.00 0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0.
For coding simplicity, follow every output value by a space, including the last one.
I have been confused about how to do floating-point values in arrays and loops as in my book it never went over that.
Scanner scnr = new Scanner(System.in);
double numElements;
numElements = scnr.nextDouble();
double [] userList = new double [numElements];
int i;
double maxValue;
for (i = 0; i < userList.length; ++i) {
userList[i] = scnr.nextDouble();
}
maxValue = userList[i];
for (i = 0; i < userList.length; ++i) {
if (userList[i] > maxValue) {
maxValue = userList[i];
}
}
for (i = 0; i < userList.length; ++i) {
userList[i] = userList[i] / maxValue;
System.out.print(userList[i] + " ");
System.out.printf("%.2f", userList[i]);
}
}
}
It's outputting:
LabProgram.java:8: error: incompatible types: possible lossy conversion from double to int
double [] userList = new double [numElements];
I am confused about how to move forward, any help will be much appreciated!
Just change the data type of numElements to int and the scanner command to int as well
Like this:
int numElements = scnr.nextInt();

Blue Pelican Java Lesson 26 Project Gymnastics

Use your new BaseClass class to implement the following project. Call
the new class Gym:
Ten people are judging an international gymnastics competition. Each
judge gives a contestant a performance score between 0.0 and 10.0,
inclusive, with the score given to one decimal place. Since some
judges favor their own country’s competitors and/or give lower scores
than deserved to their country’s rivals, the highest and lowest scores
are discarded before averaging the eight other scores. Write a program
that will read in the judges’ ten scores, discard the highest and
lowest score, and compute the average of the eight other scores to
four decimal places.
Input
Read in one or more data sets (assume you don’t know ahead of time how
many) of 10 scores from the file DataGym.in. Each data set will use
exactly one line of the input text file. There will be ten floating
point numbers (each separated from the others by spaces) between 0.0
and 10.0, inclusive (to one decimal place) on each line of the file.
Input file:
8.7 6.5 0.1 3.2 5.7 9.9 8.3 6.5 6.5 1.5
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
Output
Print, for each data set that is input, the average to four decimal
places. This average should be preceded each time by “For Competitor
X, the average score is ”, where X denotes the competitor’s position (starting with 1) in the input file.
Output to screen for above input file:
For Competitor #1, the average is 5.8625
For Competitor #2, the average is 0.0000
For Competitor #3, the average is 1.0000
My code so far:
import java.io.*;
import java.util.*;
import java.text.*;
public class Gym {
public static void main(String args[]) throws IOException {
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMinimumFractionDigits(4);
fmt.setMaximumFractionDigits(4);
Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int maxIndx = -1;
String text[] = new String[1000];
while (sf.hasNext()) {
maxIndx++;
text[maxIndx] = sf.nextLine();
}
sf.close();
for (int j = 0; j <= maxIndx; j++) {
Scanner sc = new Scanner(text[j]);
double a = 0;
double array[] = new double[1000];
double scoreAverage = 0;
int contestant = 0;
if (j <= 10) {
a = sc.nextDouble();
array[j] += a;
} else {
Arrays.sort(array);
int i = 0;
while (i < 10) {
scoreAverage += array[i];
i++;
}
}
contestant++;
String s = fmt.format(scoreAverage);
double d = Double.parseDouble(s);
System.out.println("For Competitor #" + contestant + ", the average is " + d);
}
}
}
I keep getting this:
For Competitor #1, the average is 0.0
For Competitor #1, the average is 0.0
For Competitor #1, the average is 0.0
How would I discard the highest and lowest scores?
You need to move int Contestant = 0; outside of the loop. This way it does not reset to 0 every time you go through the loop.
Also move Double sumAverage = 0; outside of the loop.

Totaling up from an array converted from a string to an integer(command line compiling)

I am compiling the code in command line with the following code typed in command line:
java aac 2 4 6 8 10
and I am getting the result:
5
The number in position 0 is 2.0
The Sum is: 2.0
The number in position 1 is 4.0
The Sum is: 4.0
The number in position 2 is 6.0
The Sum is: 6.0
The number in position 3 is 8.0
The Sum is: 8.0
The number in position 4 is 10.0
The Sum is: 10.0
What I am trying to achieve is, for the sum to be the total of all the numbers divided by the amount of numbers, however for the amount of numbers there is I have come up with a length variable. For this example the length is displayed as 5 right at the start.
public class aac {
public static void main(String args[]) {
// working out the length
int length = args.length;
System.out.println(length);
// this is a for loop that repeats until integer i is greater than
// integer length, which is the length of the args String array.
for (int i = 0; i < length; i++) {
// this string equals whatever value is in position i in string array args
String all = args[i];
// integer numConvert now equals the integer of String all
double numConvert = Double.parseDouble(all);
System.out.print("The number in position " + i + " is " + " ");
System.out.println(numConvert);
double sum = 0;
sum = sum += numConvert;
System.out.println("The Sum is: " + sum);
System.out.println();
}
}
}
Are you having problems creating the sum in order to calculate the average? If so, move the double sum = 0; out of your for loop. After the loop you divide it by args.length and that'll be your average.
Here's a little amelioration of your code :
double average = 0.0;
double sum = 0;
for(int i = 0; i < length; i++){
String all = args2[i];
double numConvert = Double.parseDouble(all);
System.out.print("The number in position "+i+" is ");
System.out.println(numConvert);
sum += numConvert;
average = sum / (i+1);
System.out.println("The Sum is: "+sum);
System.out.println("The average is :" + average);
System.out.println();
}
I created 2 double variables outside of your for loop.
Each time we loop in, the current value is added to the sum variable to get the total sum.
Also, the average is changed to the value of sum divided by the numbers we've already seen.
Here is the output :
5
The number in position 0 is 2.0
The Sum is: 2.0
The average is :2.0
The number in position 1 is 4.0
The Sum is: 6.0
The average is :3.0
The number in position 2 is 6.0
The Sum is: 12.0
The average is :4.0
The number in position 3 is 8.0
The Sum is: 20.0
The average is :5.0
The number in position 4 is 10.0
The Sum is: 30.0
The average is :6.0

PrintPowersof2 in java

Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of 2 from 20 (1) up to that maximum power, inclusive. For example, consider the following calls:
printPowersOf2(3);
printPowersOf2(10);
These calls should produce the following output:
1 2 4 8
1 2 4 8 16 32 64 128 256 512 1024
yes, this is a homework problem and I am sorry. I am not asking for code or anything just a little guidance would be helpful and I want to know what I am doing is wrong. Thank You.
import java.lang.Math;
public class Power {
public void printPowersOf2(double thisX){
double k = 1.0;
for(double i = k; i <= Math.pow(2,thisX); i++){
double square = k;
System.out.print(square+" ");
k = 2.0 * k;
}
}
}
Second Class:
import java.util.*;
public class PowerMain{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please, enter a number you want to square: ");
double exponents = input.nextDouble();
Power numberOfPower = new Power();
numberOfPower.printPowersOf2(exponents);
}
}
My output =
1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 > when i enter 3
Your issue is the line
for(double i = k; i <= Math.pow(2,thisX); i++)
The reason why is because the following code produces the value 8 when the input is 3
Math.pow(2,thisX)
If you notice, you have 8 output values which comes from 2^3. You should just be looping 3 times (instead of your current 8), so you should really just do the following
for(int i = 0; i < thisX; i++)
...
You want to get the power of 2 for each number 0 to thisX so you should change your loop like:
for(double i = 0; i <= thisX; i++)
You should be looping from 0 to your number adding 1 each loop and for each iteration take that number ^ 2 like 0^2 print 1^2 print 2^2 print 3^2 print...

String not printing out after conclusion of loop

So after browsing the already asked questions on here and other sites I figured I would give this a go.
I am working on an exercise that wants you to set up a program in Java that takes an input of 10 numbers and computes the average(mean) and the standard deviation and outputs them.
My problem is that when I run the program, and then enter my desired 10 values and hit enter, nothing happens. For some reason the System printouts that occur after the loop are not being executed. The println inside the loop is not necessary, but is just to show that the values are being calculated correctly as the loop runs, and they are.
I am aiming to have the current value that myValues is assigned to to be added to sum1, and the square of myValues to be added to the sqrdSum. sqrdSum is just a variable I made to sum the squares of the values entered so that the calculation of standard deviation later in the program will be cleaner.
As expected, I am not looking for this to be done for me, just some advice on how to adjust my code such that the printlns at that occur after the loop will execute. I am expecting it to be something to do with my logic, but can not figure it out. Hopefully it is something simple I have managed to miss.
Thanks.
So far I have set it up using a for loop:
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = input1.nextDouble();
for (int count = 0; count <= n; count++) {
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
myValues = input1.nextDouble();
}
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
The problem is, that input1.nextDouble() blocks until the next number is entered. You are entering 10 numbers, but you expect 11 inputs, since you have this line
double myValues = input1.nextDouble();
which executes once and
myValues = input1.nextDouble();
inside the loop which executes 11 times. Just move it at the beginning of the loop:
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0;
for (int count = 0; count < n; count++) {
double myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
As Brian noted, you also have an off-by-one error. You start at 0 but count to 10, that makes 11 loop cycles. Change <= to <
Just change count <= n to count < n in your cycle. You're accidentaly expecting one too many values.
While the answers given did solve your original problem there is also another problem with your code. You won't be getting the correct mean because of how you initiate it and then don't set it to any values after your for loop.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
The lines above should read,
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
and then after your for loop you should calculate mean1 and std1 like the code below.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0.0;
for (int count = 0; count < n; count++) {
myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
mean1 = sum1 / n;
std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794

Categories

Resources