Find mean and standard deviation using loops - java

My goal is to calculate the mean and standard deviation of 10 numbers obtained from user input.
I learned only while loops in my class.
Question:
How can I assign each user input (inside the loop) to a separate variable, to later compare to the mean, to find the standard deviation?
(I haven't taught about arrays in my class. So, I have to solve this without using arrays)
I did the program a very long a tedious way but can provide more code if needed to show I can do while loops to find mean.
import java.util.Scanner;
public class StandardDev
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
double num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0, total = 0, mean = 0, stDev1 = 0, stDev2 = 0, sum = 0;
System.out.println("Enter 10 numbers: ");
num1 = input.nextDouble();
num2 = input.nextDouble();
num3 = input.nextDouble();
num4 = input.nextDouble();
num5 = input.nextDouble();
num6 = input.nextDouble();
num7 = input.nextDouble();
num8 = input.nextDouble();
num9 = input.nextDouble();
num10 = input.nextDouble();
sum = num1+num2+num3+num4+num5+num6+num7+num8+num9+num10;
mean = sum / (double) 10;
stDev1 = Math.pow(num1 - mean, 2) + Math.pow(num2 - mean, 2) + Math.pow(num3 - mean, 2) + Math.pow(num4 - mean, 2) + Math.pow(num5 - mean, 2) +
Math.pow(num6 - mean, 2) + Math.pow(num7 - mean, 2) + Math.pow(num8 - mean, 2) + Math.pow(num9 - mean, 2) + Math.pow(num10 - mean, 2);
stDev2 = Math.sqrt(stDev1 / 10);
System.out.println ("The mean is " + mean + ".");
System.out.println ("The standard deviation is " + stDev2 + ".");
}
}
Here is what I have for finding mean. My logic tells me I can only find standard deviation if I can access those inputs individually to subtract from mean and square. Not sure how though..
import java.util.Scanner;
public class JTillman03_45
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int count = 0, total = 0;
double mean, stDev = 0;
System.out.println("Enter a digit: ");
int number = input.nextInt();
while (count < 9){
total += number;
count++;
System.out.println("Enter a digit: ");
number = input.nextInt();
}
mean = total / (double) count;
System.out.println("The mean of those numbers is: " + mean);
System.out.println("The standard deviation of those numbers is: " + stDev);
}
}

Do you really need to store all the integers? If not, you can compute the average and standard deviations with the three following values:
How many numbers were entered (in your problem, it is a fixed value 10).
The sum of all numbers.
The sum of the squares of the numbers.
Which gives
double count = 10.0; // is 10.0 for your problem
double sum1 = 0.0; // sum of the numbers
double sum2 = 0.0; // sum of the squares
int i;
for (i=0; i < 10; i++) {
System.out.println("Enter 10 numbers: ");
double n = input.nextDouble();
sum1 += n;
sum2 += n * n;
}
double average = sum1 / count;
double variance = (count * sum2 - sum1 * sum1) / (count * count);
double stdev = Math.sqrt(variance);

For summing up 10 user-inputted numbers, you can keep track of the sum using just one variable and the += operator. No need to have so many variables, that's what the loop is for! For example,
double sum = 0;
Scanner input = new Scanner (System.in);
int counter = 1;
System.out.println("Enter 10 numbers: ");
//adds up 10 user-inputted numbers
while(counter <= 10){
sum += input.nextDouble();
//how the loop will end after 10th iteration
counter++;
}
double mean = sum/10; //no need for double cast here since sum is a double
Without arrays, it would be hard to calculate the standard deviation using loops since we need access to the individual numbers to find the standard deviation. Therefore, your solution is really the only way unless we have the user input the same 10 numbers again using a while loop similar to above to find the variance. For example,
//reset counter
counter = 1;
double variance = 0;
System.out.println("Enter 10 numbers: ");
while(counter <= 10){
variance += Math.pow(input.nextDouble()-mean,2);
counter++;
}
double stdDev = Math.sqrt(variance/10);
System.out.println ("The mean is " + mean + ".");
System.out.println ("The standard deviation is " + stdDev + ".");

Using a while loop, iterate the values of input.nextDouble() as the condition of the loop. as long as there is input, the loop will keep going. At the same time, keep a count of the number of inputs and the sum of the numbers. Just with those 2 numbers, you can calculate the mean and the standard deviation. If you look at stDev1 you can see it is just the sum of the numbers minus the mean times 10 (or the count of inputs). The mean is just the sum divided by the count of inputs. If you need more explanations, let me know. I will be adding some example code shortly.
public class StandardDev {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
sum += input.nextDouble();
count++;
}
mean = sum / count;
stdDev = sum - (count * mean);
System.out.println("The mean is " + mean + ".");
System.out.println("The standard deviation is " + stdDev + ".");
}
}

Here is updated code with loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double sqSum = 0;
System.out.println("Enter 10 numbers: separte by space");
for ( int i = 0 ; i < 10 ; i++){
double val = input.nextDouble();
sum += val;
sqSum += val * val;
}
double mean = sum / 10;
double stdDev = sqSum / 10 - mean * mean;
System.out.println("The mean is " + mean + ".");
System.out.println("The standard deviation is " + stdDev + ".");
}

Related

How can I get standard deviation without using arrays in Java?

Using double float data calculate the count, average and standard deviation of any given input.
Every time I run the program it gives me my count and average however my standard deviation shows up as NaN.
import java.util.Scanner;
public class Final
{
public static void main (String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a range of digits to recieive 1. Count , 2. Average , 3. StdDvn");
double input = in.nextDouble();
double count = 1;
double sum = 0;
double sumsquared = sum * sum;
double std = 0;
while (in.hasNextDouble())
{ double value = in.nextDouble();
sum = input += value;
count++;
}
double average = sum / count;
std = Math.sqrt((sumsquared-(sum/count)) / (count - 1));
System.out.println("Your count of numbers is : " + count);
System.out.println("Your average of numbers is : " + average);
System.out.println("Your standard deviation of numbers is : " + std);
}
}
Your sumsquaredvariable is always 0since you calculate it from 0*0 right after the initialization of double sum=0;.
This part should be moved below the summation.
Also to calculate the standard deviation without arrays using loops, you need to know the following 3 values:
How many numbers were entered.
The sum of all numbers.
The sum of the squares of the numbers.
Formula: E[X^2]-(E[X])^2 see wikipedia.
^2 means squared of course.
public static void main (String[]args)
{
Scanner in = new Scanner(System.in);
double count = 10.0; // how many numbers are entered, e.g.: 10
double sum1 = 0.0; // sum of the numbers
double sum2 = 0.0; // sum of the squares
System.out.println("Enter 10 numbers: ");
for (int i=0; i < 10; i++) {
double n = in.nextDouble();
sum1 += n;
sum2 += n * n;
}
double average = sum1 / count;
double variance = (count * sum2 - sum1 * sum1) / (count * count);
double stddev = Math.sqrt(variance);
System.out.println("Your count of numbers is : " + count);
System.out.println("Your average of numbers is : " + average);
System.out.println("Your standard deviation of numbers is : " + stddev);
}
Your sumsquared is zero. So, you’re using a value of 0 in your standard deviation. Here’s the fix to relocate your sumsquared.
EDIT: I think your std is incorrect. You must find the mean first. Inside the square root, find the sum of ( x - mean), where x are your data, then divide that result by count - 1.
public static void main (String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a range of digits to recieive 1. Count , 2. Average , 3. StdDvn");
double input = in.nextDouble();
double count = 1;
double sum = 0;
double std = 0;
while (in.hasNextDouble())
{ double value = in.nextDouble();
sum = input += value;
count++;
}
double sumsquared = sum * sum;
double average = sum / count;
std = Math.sqrt((sumsquared-(sum/count)) / (count - 1)); /* fix this formula */
System.out.println("Your count of numbers is : " + count);
System.out.println("Your average of numbers is : " + average);
System.out.println("Your standard deviation of numbers is : " + std);
}
}

Input numbers until 0, then calculate average

Okey, i need to make a program to calculate average. But, i need to input numbers, and when i want to stop i can input zero. Then, my program need to sum all entered numbers and calculate average of entered numbers. I made almost everyithing in my code but idk how to make a formula to calculate average, my program sum numbers and then divide by last entered number.
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
int number1 = 1;
while (number != 0) {
number1 = (number + number1) / number; //here is my problem?
number = input.nextInt();
}
System.out.println("Average is: " + number1);
Your code is written great except you calculate the average wrong,
If you want to calculate the average on the fly you will need to know how much numbers you have read so far..
e.g:
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
int average = number;
int counter = 1;
while (number != 0) {
average= (average * counter + number) / (counter + 1);
counter++;
number = input.nextInt();
}
System.out.println("Average is: " + average);
this code will give you the average after each step.
Another (simpler solution) is:
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
double sum = 0;
int counter = 0;
while (number != 0) {
sum += number;
counter++;
number = input.nextInt();
}
System.out.println("Average is: " + sum/counter);
Average is the sum total of the numbers divided by the number of numbers, so you need to keep a running count of how many numbers you are inputting, as well as a running sum, and at the end, you divide the sum by the count. The sum should be a double just in case you end up with a fraction
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
double sum = 0;
int count = 0;
int number = input.nextInt();
while (number != 0) {
sum += number;
count++;
number = input.nextInt();
}
System.out.println("Average is: " + sum/count);

How do I get the sum of the first two sequences when the user enters "2" as "n"?

The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?
Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.
Thanks in advance!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}
Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.
You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).
You need to manage "1" and "2" as special cases.
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}
If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}
Output :
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75
The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}
As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......
So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.
Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.
Happy Learning Java :)

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

How to use Java to calculate average from input?

I need a program that should add x numbers. The numbers should come from user input so I need some sort of loop. I have gotten as far as shown below, but I'm stuck since I have no idea how to add a new number without deleting the previous?
System.out.println("How many numbers to use?");
int number = keyboard.nextInt();
for (int i = 0; i<number ; i++) {
System.out.println("whats the number");
double first = keyboard.nextDouble();
}
If all you need is the average, you don't need to keep all the numbers you get from user input. Just keep one variable that holds their sum.
define the sum variable outside the loop (initialized to 0), and add to it each number you get from user input.
int number = keyboard.nextInt();
double sum = 0;
for (int i = 0; i<number ; i++)
{
System.out.println("whats the number");
sum += keyboard.nextDouble();
}
double average = sum / number;
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum = 0;
int num;
System.out.println("enter how many num");
num = sc.nextInt();
System.out.println("please enter " + num + " numbers");
for (int i = 0; i < num; i++) {
sum += sc.nextDouble();
}
double avg = sum / num;
System.out.println("Average of " + num + " numbers is:" + avg);
}
}

Categories