How to calculate standard deviation using JAVA [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new here,
at the moment I am trying to calculate standard deviation with Java (I have googled it haha)
but I am having a lot of issues on getting it working
I have ten values that are inputed by a user which I then have to calculate the standard deviation of
my understanding so far thanks to people who have replied
is
I find the mean of the array
then complete the calculations
double two = total[2];
double three = total[3];
double four = total[3];
double five = total[4];
double six = total[6];
double seven = total[7];
double eight = total[8];
double nine = total[9];
double ten = total[10];
double eleven = average_total;
mean = one + two + three + four + five + six + seven + eight + nine + ten + eleven;
mean = mean/11;
//one = one - mean;
//System.out.println("I really hope this prints out a value:" +one);
*/
//eleven = average_total - mean;
//eleven = Math.pow(average_total,average_total);
//stand_dev = (one + two + three + four + five + six + seven + eight + nine + ten + eleven);
//stand_dev = stand_dev - mean;
// stand_dev = (stand_dev - mean) * (stand_dev - mean);
// stand_dev = (stand_dev/11);
// stand_dev = Math.sqrt(stand_dev);
I already have my data that is stored in an array of 10 values but I am not too sure
how to print the data out of the array then do the calculations with out having to store the enter code here
data some where else that I have manipulated
Thank you for your time, much appreciated :)

There is a simple formula that can be used to quickly calculate standard deviation every time a number is added. Here is some code that implements that formula, assuming total[] has been declared and populated already:
double powerSum1 = 0;
double powerSum2 = 0;
double stdev = 0;
for i = 0 to total.length {
powerSum1 += total[i];
powerSum2 += Math.pow(total[i], 2);
stdev = Math.sqrt(i*powerSum2 - Math.pow(powerSum1, 2))/i;
System.out.println(total[i]); // You specified that you needed to print
// each value of the array
}
System.out.println(stdev); // This could also be placed inside the loop
// for updates with each array value.
The beauty of this formula is that you don't have to reprocess the entire array each time you add a new value and you don't have to store any of the old values of the array, just the three variables declared in the code above.

calculate mean of array.
loop through values
array value = (indexed value - mean)^2
calculate sum of the new array.
divide the sum by the array length
square root it
edited:
I'll show you how to loop through the array and everything is pretty much this same step just with a different calculation.
// calculating mean.
int total = 0;
for(int i = 0; i < array.length; i++){
total += array[i]; // this is the calculation for summing up all the values
}
double mean = total / array.length;
edit2:
After reading your code, the part you are doing wrong is that you are not looping through the values and subtracting it with average correctly.
aka this part.
eleven = average_total - mean;
eleven = Math.pow(average_total,average_total);
you need to do this.
for(int i = 0; i < array.length; i++){
array[i] = Math.pow((array[i]-mean),2)
}
essentially you need to change every value in the array with newvalue = oldvalue - mean(average).
then calculate the sum... then square root that.

I won't solve your problem for you since this looks like howework, but I'll try to help you out a little by giving you some pseudocode to point you in the right direction:
Loop over array i=1 to 10
Add each element to some other variable Total
End of Loop
Average = Total / 10 (required for your std. dev. equation)
Now you need to find the distances of the elements from the mean. Easy
Loop over array i = 1 to 10
Replace each element with its distance from Average Squared
Add to some variable differenceTotal
End of Loop
Then you have your numerator and denominator terms, and your solution should be obvious. Hopefully that was somewhat clear and helpful.

Try this
import java.io.IOException;
public class StandardDeviationCalc {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
double [] values = {9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10,
9, 6, 9, 4 }; //change input values here
double sum=0;
double finalsum = 0;
double average = 0;
for( double i : values) {
finalsum = (sum += i);
}
average = finalsum/(values.length);
System.out.println("Average: "+ average);
double sumX=0;
double finalsumX=0;
double[] x1_average = new double[2000];
for (int i = 0; i<values.length; i++){
double fvalue = (Math.pow((values[i] - average), 2));
x1_average[i]= fvalue;
System.out.println("test: "+ fvalue);
}
for(double i : x1_average) {
finalsumX = (sumX += i);
}
Double AverageX = finalsumX/(values.length);
System.out.println("E(X1-x1_average)^2/AverageX: "+ AverageX);
double SquareRoot = Math.sqrt(AverageX);
System.out.println("Standard Deviation: "+ SquareRoot);
}
}
You can tweak to how u want like adding user input.The code is rough becose I assume this is a homework. try to make it nice in your own way. hope it helps you.

What have you tried?...
You will need to loop the values for example to print all the values
for(int i = 0; i < yourArray.length; i++)
{
System.out.println(yourArray[i]);
// Add your code to calculate the values you need for standard dev
}

Related

How can I find out the four unique random numbers in Android within the range of 1 to 60?

This is what I tried so far in my app.
I got this code by searching it from Google.
Inside the Button OnClick() I called the Arandom() method:
public void Arandom(View view) {
final int SET_SIZE_REQUIRED = 4;
final int NUMBER_RANGE = 70;
Random random = new Random();
Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);
while(set.size()< SET_SIZE_REQUIRED) {
while (set.add(random.nextInt(NUMBER_RANGE)) != true) ;
}
assert set.size() == SET_SIZE_REQUIRED;
ArrayList<Integer> Elements = new ArrayList<>(set);
Log.i("Elements","A:" + Elements.get(0));
Log.i("Elements","B:" + Elements.get(1));
Log.i("Elements","C:" + Elements.get(2));
Log.i("Elements","D:" + Elements.get(3));
}
Now I am able to get four unique random numbers by this code but the problem is there sum is greater then 60. Let me explain it little bit.
When I run the code I get:
A:61
B:45
C:31
D:49
This is the screen shot of my log cat
So I want the sum of all the numbers should be in the specified range (which is 1 to 60).
e.g: A = 20 , B = 25 , C = 3 and D = 11 then their sum is 59 which is within the range
Now another e.g: Suppose A = 5 , B = 22 , C = 18 and D = 3 then their sum will be 48
When we Add A,B,C,D then their sum should not exceed the range that is 60
I am new to Android and Java, and I am learning on my own by searching some materials on Google.
Let's say your target sum is T. It's easiest if you try to pick the numbers in descending order (you can shuffle them afterwards, if you want).
The largest number you can pick for the 1st of four numbers is T-6, because you need to pick 3, 2 and 1 for the smaller numbers.
The smallest number you can pick is the one where n+(n-1)+2+1 = T, so T/2+1.
So, pick the first number in the range (T/2+1) to T-6.
Then repeat the process to pick the third-largest and second-largest, applying similar logic to determine the possible range. There should be no choice in the smallest number, it's just whatever else you need to add to make the final sum.
Note that you need to take care with rounding of things like the T/2.
I made the return type an int[]. You know how big you want to make the set, so there is no need to use sets or lists. The input parameter is changed to SET_SIZE_REQUIRED instead of using view. Make sure that a funtion only has one purpose and not do a calculation and change on a view at the same time.
Replace the 60f to something else if you want the sum to be more or less than 60.
public int[] Arandom(int numberOfValues) {
int[] values = new int[numberOfValues];
int sum = 0;
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(Math.random() * 100);
sum += values[i];
}
float multiplier = 60f / sum;
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(values[i] * multiplier);
Log.i("Value " + (i + 1), values[i]);
}
return values;
}
Or just do this:
public int[] Arandom(int numberOfValues) {
int[] values = new int[numberOfValues];
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(Math.random() * (60f / numberOfValues));
Log.i("Value " + (i + 1), values[i]);
}
return values;
}

Calculate Standard Deviation using Java?

I have an ArrayList of integers: [11, 15, 10, 19, 9, 1, 2, 16]
and I can't seem to return the right answer.
My code:
static double Q2(ArrayList<Integer> input) {
Collections.sort(input);
ArrayList<Double> input2 = new ArrayList<>();
double sum = 0;
double sum2 = 0;
double sd = 0;
for (int i = 0; i < input.size(); i++) {
sum = sum + input.get(i);
}
double mean = sum / input.size();
for (int i = 0; i < input.size(); i++) {
input2.add((Math.pow((input.get(i) - mean), 2)));
}
for (int i = 0; i < input2.size(); i++) {
sum2 = sum2 + input2.get(i);
}
double mean2 = sum2 / input2.size();
sd = Math.sqrt(mean2);
return sd;
The Expected output should be: 5.998697775350913
My output is : 6.010407640085654
Thank you for your time, much appreciated.
Although mathematically correct, this is, computationally, a terrible way to compute SD. There is no need to sort the inputs first. There is no need to create a second array to store the squared deviations; you can just add them as you go in one loop. There is no need to call Math.Pow instead of just computing z * z.
Fix all that, and you will have improved this approach as much as you can. But a better approach entirely is to use an online algorithm, which can do it in one pass.
Finally, be aware that in many cases when people ask you to compute the SD, they actually want the population SD, not the sample SD, which requires you to divide the sum of squared deviations by (n-1) instead of n.

Adding and finding the average in an array

I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.
import javax.swing.*;
public class SumAverage {
public static float sum;
public static float averageCalculator;
public static float average;
public static void main(String[]args) {
float numbers[] = null;
String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
if(userInput.equalsIgnoreCase("no"))
{
System.exit(0);
}
for(int i = 0; i != -2; i++)
{
numbers = new float[i + 1];
userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
{
break;
}
else
{
numbers[i] = Float.parseFloat(userInput);
}
}
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
average = sum / numbers.length;
JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
}
}
The problem is in this line:
numbers = new float[i + 1];
You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.
You can fix this in two ways:
copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers)
Don't use arrays! Use a List<Float> instead, which automatically grows in size
In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.
If you wanted to store the numbers for later use, try making your code look like this:
List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
sum += n;
}
average = sum / numbers.size(); // Note: Don't even need a count variable
And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.
Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:
count = 0
sum = 0
while value = getUserInput():
count++
sum += value
print "average:" + (sum / count)
with
numbers = new float[i + 1];
you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.
Delete this line and initialize the array before.
If the size of the array should grow dynamically within the loop
do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.
Further i would suggest to use
while (true) {
//...
}
to realize an infinite loop.

Possible loss of precision error Java

Quick question, I found answers close to this but nothing that helps me. I want it to print out a percentage at the end of the code that has 4 numbers after the decimal point, and of course, using an int work work. But using floats gives me an error.
This code:
import java.util.Scanner;
public class HW2johnson_pp4 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("How many numbers will you enter?\n");
float[] numbers = new float[keyboard.nextFloat()];
System.out.printf("Enter " + numbers.length + " integers, one per line:\n");
for (int i = 0; i <= numbers.length - 1; i++) {
numbers[i] = keyboard.nextInt();
}
float sum = 0;
for (int i = 0; i <= numbers.length - 1; i++) {
sum += numbers[i];
}
System.out.printf("The sum is " + sum + "\n");
System.out.printf("The numbers are:\n");
for (int i = 0; i <= numbers.length - 1; i++) {
float perc = (numbers[i] / sum);
float perct = (perc * 100);
System.out.printf(numbers[i] + " which is " + perct + "%% of the sum.\n");
}
}
}
Gives the error:
HW2johnson_pp4.java:8: possible loss of precision
found : float
required: int
float[] numbers = new float[keyboard.nextFloat()];
You can't create an array of floats whose length is a floating-point value. That is to say, you can't have an array with 2.7 elements.
So the float within the length parameter is getting rounded, causing a loss of precision.
You wanted keyboard.nextInt() there on line 8, and keyboard.nextFloat() below on line 13.
You cannot initialize an array with floating point values.
float[] a = new float[4]
And not
float[] a = new float[4.0]
So, The problem is here:
float[] numbers = new float[keyboard.nextFloat()];
Use keyboard.nextInt() instead.
You're using keyboard.nextFloat(), which is a float, as the length of the array numbers. The length of an array has to be an int.
Thats because in line 8 you are making a new array, and passing a float as the length. Since all arrays require an integer as an array length, it will convert the float to an integer, and gives an error. You want to pass in an integer value.

Java unknown output

Soo this problem involves me rolling a pair of dice and estimate the probability that the first roll is a losing roll (2, 3, or 12).
output is the count of rolls that were losers (2,3, or 12) and calculated probability (count/N)
public static void main(String [] args){
int N1 = (int) (Math.random()*6 + 1);
int N2 = (int) (Math.random()*6 + 1);
int count = N1 + N2;
for (int i = 0; i<=1; i++)
if (count==2 || count = 3 || count == 12)
I just don't seem to know what to do get the output...... This is my attempt
It seems that you will want to roll the dice N times (where N is some large number) and count the number of times that it was a loser, correct?
So you will need to store in memory the total number of rolls, and the number of losing rolls. You can store those in int variables.
An int variable can be incremented using the ++ operator.
int rolls = 0;
rolls++;
is equivalent to
int rolls = 0;
rolls = rolls + 1;
You also don't want to call your main function a million times, so you can set the upper limit of your loop to the amount of rolls you want to have.
To calculate the probability, you will want to use floats rather than ints - you can cast an int to a float like this:
int a = 10;
float b = (float) a;
Finally, if you want to see your output via standard out, use System.out.println(). The argument to the println() function should be whatever you want to output.
Since this sounds like homework, I'm avoiding writing much code for now. Let me know if it isn't.
The simplest way to get output from a command-line app (like you are writing) is to use System.out.println(...). For example:
int digits = 5;
System.out.println("Hello world");
System.out.println("I have " + digits + " fingers");
This should be enough of a hint for you to make progress.

Categories

Resources