How can I get standard deviation without using arrays in Java? - 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);
}
}

Related

what is wrong with my standard deviation calculation?

my code to find standard deviation is wrong. my code is supposed to find standard deviation from user input. i typed in the numbers 1 2 3 and the standard deviation of this set of numbers is 1 but it printed 10 where did i go wrong. also i know i have a bunch of unused variables dont mind them.
import java.util.Scanner;
public class readFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n;
int i;
int count=0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average=0;
int sum;
double deviation = 0;
int total;
int temp = 0;
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
inStr = input.next();
average += n;
temp += Math.pow(n - average, 2);
}
deviation = temp
average = average/count;
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
System.out.printf("The standard deviation of the list is %d\n", temp);
input.close();
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n = 0;
int i;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average = 0;
int sum;
double deviation = 0;
int total;
double temp = 0;// correction here because it must store double or float value
ArrayList<Integer> n1 = new ArrayList<Integer>();// i used this to store all entered values
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
n1.add(n);
inStr = input.next();
average += n;
}
average = average / count; // this will give you final average
for (int j = 0; j < count; j++) {
temp += Math.pow(n1.get(j) - average, 2);
}
//System.out.println("\n" + temp + " " + count);
deviation = Math.sqrt(temp / count); // this is your standard deviation
//System.out.println(deviation);
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
System.out.println("The standard deviation of the list is " + deviation);
input.close();
}
}
Standard deviation for one variable is defined here. You have to take the square root of the mean of the sum of the squared differences between observations and the mean of the set.
//in the loop
temp += Math.pow(n - average, 2)
//outside the loop
deviation = Math.pow(temp/count,0.5) //or alternatively Math.sqrt()
This should give you what you need.

Find mean and standard deviation using loops

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 + ".");
}

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.

why is my count increasing when entering 0, it should exit the loop

I been working on this all night but couldn't make anything out it. I want my code to sum all the numbers the user enter, count how many times the user enters the number. then calculate the average.
and then find the max and min, easy right. well yeah if i was to be allowed to use arrays but this is for review and I hate while loops.
here's my code.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
Here's the output:
Please enter an integer:
3
The sum of your numbers is: 3.0
The number of values entered is: 1
Please enter an integer:
2
The sum of your numbers is: 5.0
The number of values entered is: 2
Please enter an integer:
1
The sum of your numbers is: 6.0
The number of values entered is: 3
Please enter an integer:
0
The sum of your numbers is: 6.0
The number of values entered is: 4
The average of your sum is: 1.5
The max integer is: 3.0
The min integer is: 0.0
when the count increases by 1 my average comes out wrong. but why is 0 been counted as part of count and why my min always output 0 and not what the user enters. any and all help is much appreciated.
p.s. i have tried numerous ways but it doesnt work. if i try to change my count to start at -1 it solves my problem at hand with average but the count increases anyways so i know its incorrect. also the min problem stays there.
thanks guys
You need to add if condition to avoid increment when you enter 0.
You can use this code
// setting starting min and max value.
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
if (integer != 0) { // added if condition
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min) // changed 'else if' to 'if'
min = integer;
}
}
System.out.println("Max : " + max);
System.out.println("Min : " + min);
Try this:
For these cases it is best to use the conditional do while. And initialize min at the maximum value allowed.
double integer;
double sum = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = 0;
do {
System.out.print("Please enter an integer: ");
integer = input.nextInt();
if (integer >0) {
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
} while (integer != 0);
System.out.println("avg: "+sum/count);
System.out.println("max: "+max);
System.out.println("min: "+min);
you will need to add an extra if condition to make it work.
I have made few changes as below in your code and it is working as expected.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = integer;
double max = integer;
while (true) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
if(integer != 0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
break;
}
double integer = 1;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer(press zero to exit): ");
integer = input.nextInt();
if (integer > 0){
sum += integer;
count++;
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
}
System.out.println("The sum of your numbers is: " + sum);
System.out.println("Your count number is: " + count);
average = sum / count;
System.out.println("The average of your sum is: " + average);
System.out.println("The max integer is: " + max);
System.out.println("The min integer is: " + min);
}
}
You may try the below code
import java.util.Scanner;
public class ComputeDemo {
public static void main(String[] args) {
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer=input.nextInt();
if(integer>0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
{
min=0;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
}
}
}
}

Write a program that reads an unspecified number of integers

"Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers , determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number."
I don't know what I did wrong
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is %d ", average);
}
}
First: it should be average = (double)total / count; because int / int than you get an integer.
Second: System.out.println("The average is " + average); or System.out.printf("The average is %f ", average);
If you want the average of numbers, you cannot divide an integer total by an integer count because the result will be an integer, which does not account for decimal points.
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = (double) total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is: " + average);
}
}
Also, you don't have to use %d in your line System.out.printf("The average is %d", average);
You can write System.out.printf("The average is: " + average); because when you print out a String, anything concatenated within the parentheses will also be converted to a String, and printed out as such
Simply multiply your int variable by 1.0 to convert it into floating point variable
average=1.0*total/count;
This should do.
And you can use following statement to display the value
System.out.println("The average of numbers is "+average);
// Scanner is in java.util package
import java.util.Scanner;
class CountPandN
{
public static void main(String args[])
{
// create a Scanner object
Scanner input = new Scanner(System.in);
// prompt user to enter numbers
System.out.println("Enter + and - numbers");
System.out.println("Enter 0 when you're finished");
// initialize the variables
int n, countP, countN, count;
n = input.nextInt();
countP = 0;
countN = 0;
count = 0;
int sum = n;
float average = (float) sum / 2;
while (n != 0)
{
n = input.nextInt();
count++;
if(n >= 0)
countP++;
if (n < 0)
countN++;
}
System.out.println("Total positive " + countP);
System.out.println("Total negative " + countN);
System.out.println("Total numbers " + count);
System.out.println("Total average " + average);
}
}
if you simply change System.out.printf("The average is %d ", average); with System.out.printf("The average is " +average); i.e. if you remove%d and use '+'instead ',' then it will work for you, and also to get answer in float you need to use typecasting. i.e. add (double) in average = (double)total / count;

Categories