what is wrong with my standard deviation calculation? - java

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.

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);
}
}

Finding the lowest value in the array

int min = temperature[0];
//Here, i have initialized the minium array.
else if(temperature[i] < min) {
min = temperature[i];
And here i have compared the values in the array. But as the initialization of min is 0. It is going to minimum value zero all the time. How do i fix it. Here is my whole code.
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = temperature[0];
int max = temperature[0];
int counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
if (temperature[i] > max) {
max = temperature[i];
}
else if(temperature[i] < min) {
min = temperature[i];
}
}
int average = counter / temperature.length;
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
}
}
Remove the else, logically - if the value is less than the current minimum we want to update current minimum (regardless of the state of the current maximum). We can actually make it clearer using Math.max(int, int) and Math.min(int, int). And, we can't default min and max to initial values without having read the input (unless we use unambiguously absurd values). Like,
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
max = Math.max(max, temperature[i]);
min = Math.min(min, temperature[i]);
}
int average = (int) (counter / (double) temperature.length);
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
Otherwise, you need two loops. Finally, note you were using integer math in calculating average. You presumably want floating point math.
Or, even better, use IntSummaryStatistics like
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
}
IntSummaryStatistics iss = IntStream.of(temperature).summaryStatistics();
System.out.println("Displaying the average temperature:" + iss.getAverage());
System.out.println("The lowest temperature is:" + iss.getMin());
System.out.println("The highest temperaature is:" + iss.getMax());
System.out.println("The total of all values is:" + iss.getSum());
The solution is to initialize min to the first value of your array, if the array had at least one value. You could also set it to Integer.MAX_VALUE if you really want.

Min Max values of a random Array

I am having some issues getting my min and max values to print. Also as new
as I am to programming I don't understand why all my values are decimals. I will post the code and my results.
import java.util.Random;
import java.util.Scanner;
import java.util.*;
public class RandomArray1
extends ArrayList<Double>
{
private static final long serialVersionUID = 1L;
public RandomArray1()
{
super();
}
public static RandomArray1 getInstance(int size)
{
Random randomNumberGenerator = new Random();
RandomArray1 randomArray = new RandomArray1();
for (int i = 0; i < size; i++)
{
randomArray.add(randomNumberGenerator.nextDouble());
}
return randomArray;
}
public Double getAverage()
{
if (this.size() == 0)
{
return 0d;
}
Double sum = 0d;
for (Double element : this)
{
sum = sum + element;
}
return sum / this.size();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many numbers you would like to Generate: ");
RandomArray1 randomArray = RandomArray1.getInstance(scan.nextInt());
System.out.println(randomArray);
System.out.println("Average" +randomArray.getAverage());
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
while (true) {
if ( !scan.hasNextDouble())
break;
Double num = scan.nextDouble();
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
}
Here are my results...
Enter how many numbers you would like to Generate: 5
[0.8630040934474159, 0.12949667753808425, 0.5751777190226718, 0.18492672539115063, 0.7508377917335503]
Average : 0.5006886014265746
always decimal point and it doesn't even print "Max is:" or "Min is:" which makes me think something is wrong with this section. But I don't know what it is...any thoughts. Just ideas...
while (true) {
if ( !scan.hasNextDouble())
break;
Double num = scan.nextDouble();
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
I think you're filling you're array with nextDouble() which as documented gives you double precision floating point numbers between 0 and 1.
All good, changed the Arraylist to an Integer and everything else. This solved my issues as discussed. here is what the code looks like now...works perfect!
import java.util.*;
public class RandomArray1
extends ArrayList<Integer>
{
private static final long serialVersionUID = 1L;
public RandomArray1()
{
super();
}
public static RandomArray1 getInstance(int size)
{
Random randomNumberGenerator = new Random();
RandomArray1 randomArray = new RandomArray1();
for (int i = 0; i < size; i++)
{
randomArray.add((int) randomNumberGenerator.nextInt());
}
return randomArray;
}
public Double getAverage()
{
if (this.size() == 0)
{
return 0d;
}
Double sum = 0d;
for (Integer element : this)
{
sum = sum + element;
}
return sum / this.size();
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many numbers you would like to Generate: ");
RandomArray1 randomArray = RandomArray1.getInstance(scan.nextInt());
System.out.println(randomArray);
System.out.println("Average : " +randomArray.getAverage());
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
for (int num : randomArray)
{
min = Math.min(min, num);
max = Math.max(max, num);
}
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
thank you so much!
Your program works fine:
Enter how many numbers you would like to Generate: 3
[0.26063976207509887, 0.48867331377683443, 0.3864751544223266]
Average0.37859607675808665
4
Max is: 4.0
Min is: 4.0
5
Max is: 5.0
Min is: 4.0
3
Max is: 5.0
Min is: 3.0
end
But since it expects an input, but doesn't say so, it could appear to be "dead". Just include a prompt before waiting for the next input:
System.out.print("Please enter next number: ");
if ( !scan.hasNextDouble())
break;
In case you wanted to calculate the min/max of the existing array instead of a new user input, use a for loop to iterate over the existing array:
for (double num : randomArray) {
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

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