Java programming standard deviation error in code - java

My standard deviation is way off. When I enter:
2 4 4 4 5 5 7 9 n
I don't get 2. This is my code. I believe everything checks out so I don't understand why I keep getting 1.8284791953425266 instead of 2 :
import java.util.Scanner;
public class stocks {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double currentNum = 0;
double numtotal = 0;
int count = 0;
double mean = 0;
double square = 0, squaretotal = 0, sd = 0;
System.out.println("Enter a series of double value numbers, ");
System.out.println("Enter anything other than a number to quit: ");
while (in.hasNextDouble())
{
currentNum = in.nextDouble();
numtotal = numtotal + currentNum;
count++;
mean = (double) numtotal / count;
square = Math.pow(currentNum - mean, 2.0);
squaretotal = squaretotal + square;
sd = Math.pow(squaretotal/count, 1/2.0);
}
System.out.println("The mean is: " +mean);
System.out.println("The standard deviation is: " +sd);
}
}

You need to work out the mean for all the numbers before you work out the standard deviation.
Right now your mean is the average of all numbers up to the current number. Your problem is here
square = Math.pow(currentNum - mean, 2.0);
At this point the mean is the average of the numbers we've seen. This is because numtotal is the total of the numbers we've seen. To fix this you can take in all the numbers first into something like an array-list. Then work out the mean with all the numbers and after that you can work out the square differences and so the standard deviation.

count needs to be a double if you're going to divide by it.
mean = (double) numtotal / count;
-->
mean = (double) numtotal / (double) count;

Related

Java - Varied amount of input data- specific format of output

Instructions;
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics. Assume the input contains at least one non-negative integer.
Output the average with two digits after the decimal point followed by a newline, which can be achieved as follows:
System.out.printf("%.2f\n", average);
Ex: When the input is:
15 20 0 3 -1
the output is:
20 9.50
I have tried a few different ways to convert the int avg into a string but somehow keep messing up.. What am I not doing?? Example code below
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
String s=Integer.toString(avg);
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.printf("%.2f\n", avg);
}
}
What you are trying to do is almost correct. The only things, you would need to change for this to work are these:
int avg = 0; // The type of avg should be a float
The reason for this is that what you're printing is a float but before these changes, you are providing it with an int.
// The number you are providing avg with should be cast to a float value
avg = total/(count-1);
This is because if you didn't, you would have integer division.
// It would look like this
float avg = 0;
avg = (float)total/(count-1);

My program does not output the right decimal numbers of an arithmetic average. How can I fix it?

I need to display the correct arithmetic average of a series of integers entered by the user.
If the user enters 6, 9, 7, and 4, the average should be 6.5 but instead displays 6.0. Why does that happen? I used an ArrayList to store all the integers.
import java.util.Scanner;
import java.util.*;
import java.util.Collections;
public class QuizScoreStatistics
{
public static void main(String[] args) {
List<Integer> Scores = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int i = 0;
int a = 0;
while(a != 99) {
System.out.println("Enter scores");
a = input.nextInt();
if(a != 99) {
if ( a > 10 || a < 0) {
System.out.println("Score must be between 10 and 0");
}
else {
Scores.add(a);
}
i++;
}
}
int max = Collections.max(Scores);
int min = Collections.min(Scores);
int sum = 0;
double averg = 0;
for( i = 0; i <= Scores.size() - 1; i++) {
sum += Scores.get(i);
}
averg = sum / Scores.size();
System.out.println("Scores entered " + i);
System.out.println("Highest score " + max);
System.out.println("Lowest score "+ min);
System.out.println("Average: "+ averg);
}
}
I won't try to give away the entire question I think you could probably answer that yourself given a nudge in the right direction.
You correctly identified that your averg is a double because your answer could come out to something like 6.7 or 2.3 or whatever. Thats a correct assumption to make! However during your "arithmetic process" you are using integers to do the division, which will come out as an integer. I will repeat the actual DIVISION is happening with two integers , can you see where the bug is coming from?
If you need more of a push to see the exact remedy of this solution I would point you here
https://programming.guide/java/wrong-results-for-division.html
Try averg = (1.0 *sum) / Scores.size(); because int/int => int but double/int=>double
Ok, this is how the operator "/" works.
int / int => int
int / float => float
float / int => float
Since you are doing an int division (int/int), the result will be an int, losing decimal information. If you want your division to be float or double, you have two options, either you declare the sum as double or you can just cast the division, so it becomes a double division instead of an int division.
averg = (double) sum / Scores.size();

How to find out variance from array of numbers?

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

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

Finding average of a text file

I am fairly new to java and I'm trying to code to find the average. I understand that the average is adding all the numbers and then dividing the sum by the number of numbers but I'm not really sure how to code that. My guess is that I'd need a for loop but I don't know what to do from there. The program basically asks for a file to be read and then calculate the average. Here's the code I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
int length = reader.nextInt();
double [] num = new double[length];
double [] num2 = new double[length];
System.out.println("The numbers are:");
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
System.out.println(num[i]);
}
}
}
The file I would be using is list.txt which contains:
20
1.1 2 3.3 4 5.5 6 7 8.5 9 10.0
11 12.3 13 14 15.5 16.1 17 18 19.2 20.0
The mean should be 10.625. Any help is deeply appreciated. Thank you in advance.
Just introduce a new variable sum, initialize it to 0, and add the elements to the variable while you are printing them.
System.out.println("The numbers are:");
double sum = 0; //new variable
for(int i = 0; i < length; i++)
{
num[i] = reader.nextDouble();
sum += num[i];
System.out.println(num[i]);
}
sum /= (double) length; //divide by n to get the average
System.out.print("Average : ");
System.out.println(sum);
It appears that you're simply having trouble computing the average; I'll address that issue here:
In Java 7 and below, use a for loop:
double sum = 0; //declare a variable that will hold the sum
//loop through the values and add them to the sum variable
for (double d : num){
sum += d;
}
double average = sum/length;
In Java 8 you can use a Stream to compute the average
double sum = Arrays.stream(num).sum(); //computes the sum of the array values
double average = sum/length;

Categories