Calculate Standard Deviation using Java? - 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.

Related

Solving a matrix equation in Java

I have been trying to implement the given formula in JAVA but i was unsuccessful. Can someone help me find what I am doing wrong?
Do i need to shift the summation index and if so how?
My code:
public final class LinearSystem {
private LinearSystem() {
}
public static int[] solve(int [][]A , int []y) {
int n = A.length;
int[] x = new int[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k == n; k++) {
sum += A[i][k]*x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
int[][]A = new int[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
int [] y = new int[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); **// awaited result [2, -3, 1]**
}
}
Just trying to collect all my comments under the question into one coherent answer, since there are quite a few different mistakes in your program.
This method of solving linear equations relies on your calculating the components of the answer in reverse order - that is, from bottom to top. That's because each x[i] value depends on the values below it in the vector, but not on the values above it. So your outer loop, where you iterate over the x values needs to start at the biggest index, and work down to the smallest. In other words, instead of being for (int i = 0; i < n; i++), it needs to be for (int i = n - 1; i >= 0; i++).
The inner loop has the wrong stopping condition. With a for loop, the part between the two semicolons is the condition to continue iterating, not the condition to stop. So instead of for(int k = i + 1; k == n; k++), you need for(int k = i + 1; k < n; k++).
You're doing an integer division at the beginning of 1 / A[i][i] * (y[i] - sum);, which means the value is rounded to an integer before carrying on. When you divide 1 by another integer, you always get -1, 0 or 1 because of the rounding, and that makes your answer incorrect. The fix from point 4 below will deal with this.
The formula relies on the mathematical accuracy that comes with working with either floating point types or decimal types. Integers aren't going to be accurate. So you need to change the declarations of some of your variables, as follows.
public static double[] solve(double[][] A, double[] y)
double x[] = new double[n];
double sum = 0.0;
along with the corresponding changes in the main method.
First, you need the second loop to go until k < n, otherwise this throws the ArrayOutOfBounds Exceptions.
Second, you need to calculate your x in reverse order as #Dawood ibn Kareem said.
Also, you probably want x[] to be a double-array to not only get 0-values as result.
I am sorry I don't know much about math side so I couldn't fix it to the right solution but I noticed a few things wrong about your code.
1-You shouldn't initialize your arrays as integer arrays, because you will be doing integer division all over the place. For example 1/A[i][i] will result in 0 even if A[i][i] = 2
2-You shouldn't write k == n, if you do it like this then your for loop will only execute if k equals n, which is impossible for your case.
I think you want to do k < n, which loops from i+1 to the point where k = n - 1
Here is my code:
import java.util.Arrays;
public final class LinearSystem {
private LinearSystem() {
}
public static double[] solve(double [][]A , double []y) {
int n = A.length;
double[] x = new double[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k < n; k++) {
sum += A[i][k] * x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
double[][]A = new double[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
double [] y = new double[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); // awaited result [2, -3, 1]**
}
}
Remember that arrays are indexed from 0, so the last element is at index n - 1, not n.

What to change in my code to calculate sample Standard deviation instead of population standard deviaiton?

My code calculates the population deviation when I need it to calculate the sample deviation I have compared both formulas and tried changed my calculations but nothing seems to work. Thanks for everyone's help or input in advance.
public class MeanAndStandardDeviation {
public static void main (String argv []) throws IOException {
BufferedReader stdin =
new BufferedReader (new InputStreamReader (System.in));
NumberFormat nf = new DecimalFormat ("0.00");
nf.setMinimumFractionDigits (2);//Sets Min digits
nf.setMaximumFractionDigits (2);//Sets Max digits
String inputValue;
int count = 0;
//For Loop for count
for(int i = 0; i < count; i++){
count++;
}
double varianceFinal = 0;
List<String> input = new ArrayList<String>();//String ArrayList
List<Double> numbers = new ArrayList<Double>();//Double ArrayList
//While loop that takes in all my input and assigns it to the ArrayLists
//Parameters set for when null is entered and total numbers go over 500
while((inputValue = stdin.readLine()) != null && !inputValue.equals("") && input.size()<500){//Parameters set for when null is entered and total numbers go over 500
input.add(inputValue);
numbers.add (Double.parseDouble(inputValue));
}
System.out.println ("Standard Deviation: " +(nf.format(calcStdDev (numbers, count, varianceFinal))));//Prints the Standard Deviation
}
//StandardDeviation Class
static double calcStdDev (List<Double> numbers, int count, double variance){
variance = 0;
double sum = 0;
for(int i = 0; i < numbers.size(); i++){
sum += numbers.get(i);
variance += numbers.get(i) * numbers.get(i);
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
}
Seriously, your code is "wrong" on many levels. So instead of debugging all of that for you, I will give you some hints how to fix and simplify your code - then it should be very easy for you to fix/resolve your actual math problem.
First of all, your code is so written in a confusing style that just makes it much harder to understand (and therefore debug) than it needs to be.
Example:
int count = 0;
//For Loop for count
for(int i = 0; i < count; i++){
count++;
}
That for loop doesn't do anything. And even when the condition would be something else, like i < someNumber; you would still just need to put count = someNumber there; instead of looping!
Same here: what is the point of providing count as argument to your calc methods?! And to then just increase it? So, lets rewrite that:
public static double calcStdDev (List<Double> numbers, double variance) {
double sumOfNumbers = 0;
double sumOfSquares = 0;
for(double number : numbers) {
sumOfNumbers += number;
sumOfSquares += number * number;
}
... and instead of calculating count, you simply have
int numberOfNumbers = numbers.size();
... and now, do your math
The other thing that is really strange in your code is how you setup your variance variable; and how it is used within your calc methods.
Long story short: step back and remove everything from your code that isn't required.
It is a bad idea to compute the variance as you do. If the mean is largeish, eg 10 million, and the noise is smallish, eg around 1 then the limited precision of doubles may well mean that your computed variance is negative and the the sd will be nan.
You should either compute it in two passes, eg
double mean = 0.0;
for( i=0; i<n; ++i)
{ mean += x[i];
}
mean /= n;
double var = 0.0;
for( i=0; i<n; ++i)
{
double d = x[i] - mean;
var += d*d;
}
var /= n;
or in one pass, eg
double mean = 0.0;
double var = 0.0;
for( i=0; i<n; ++i)
{
double f = 1.0/(i+1);
double d = x[i]-mean;
mean += d*f;
var = (1.0-f)*(var + f*d*d);
}
(it takes a bit of tedious algebra to show that the one pass method gives the same answer as the two pass method).

How to calculate the percentage of even numbers in an array?

i am beginner and here is the method I am struggling with.
Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.
here is what I have so far...
public static double percentEven(int[]a){
int count = 0;
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent =(count/a.length)*100.0;
}
return percent;
}
i keep returning 0.0 when array contains a mix of even and odd elements but works fine for all even element array or all odd array? i can't see where the problem is?
thanks in advance.
count/a.length returns 0 since you are dividing two ints, and the second operand is larger than the first. Change it to (double)count/a.length in order to perform floating point division.
Alternately, change the order of operations to :
percent = 100.0*count/a.length;
For a simple division like 2*100.0/5 = 40.0, the above logic would work fine but think about the situation where we have 51*100.0/83 the output would be less readable and its always advisable to truncate the percentage to a limited decimal digits.
An example:
int count = 51;
Double percent = 0.0;
int length = 83;
percent = count*100.0/length;
System.out.println(percent);
output: 61.44578313253012
When you truncate it:
Double truncatedDouble = new BigDecimal(percent ).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(truncatedDouble);
output: 61.446
#Bathsheba : Well said, thanks for the suggestion.
Here is sample code :
public class PercentEven {
public static void main(String args[]){
int count = 0;
int[] a={2, 5, 9, 11, 0}; // this can be dynamic.I tried diff values
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent = (100*count/a.length);
}
System.out.println(percent);
}
}
List<Integer> numbers = Arrays.asList(a);
int number = numbers.stream().filter(n->n%2==0).count();
int percent = number*100.0/numbers.size();
I have done this in java 8

Find All Possible Paths Algorithm

Hello there StackOverFlow! I am posting here today because I have a problem here in Java where I am trying to compute the all the possible combinations of pogo sticks that my character may use to move. The character uses pogo sticks which all have a distance, given by user input.
Likewise, the total distance is also given via user input and all possible paths are to be found. I have shown my function below with the output and the desired output that I can't seem to get quite right.
I have been stuck on this problem for a while and I am really hoping somebody can help me out here!
/*
* First integer in input
*/
int totalDistance;
/*
* The remaining integers in the input
*/
ArrayList<Integer> pogoSticks = new ArrayList<Integer>();
private void findPaths() {
ArrayList<ArrayList<Integer>> possibleSticks = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < pogoSticks.size(); i++) {
int pogoStickDistance = pogoSticks.get(i);
if (pogoStickDistance == totalDistance) {
if (!possibleSticks.contains(new ArrayList<Integer>(pogoStickDistance))) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(pogoStickDistance);
possibleSticks.add(list);
}
} else if (pogoStickDistance < totalDistance) {
int remainingDistance = totalDistance;
ArrayList<Integer> possibleSubSticks = new ArrayList<Integer>();
possibleSubSticks.add(pogoStickDistance);
remainingDistance -= pogoStickDistance;
for (int j = 0; j < pogoSticks.size(); j++) {
int pogoStickDistance1 = pogoSticks.get(j);
if (pogoStickDistance1 == remainingDistance) {
possibleSubSticks.add(pogoStickDistance1);
possibleSticks.add(possibleSubSticks);
break;
} else if (pogoStickDistance1 < remainingDistance) {
possibleSubSticks.add(pogoStickDistance1);
remainingDistance -= pogoStickDistance1;
}
if (j == (pogoSticks.size() - 1) && pogoStickDistance1 != remainingDistance) {
j = 0;
}
}
}
}
System.out.println(possibleSticks);
}
Here is the output that I get from running the function above:
Enter input: 5 10 4 1 2
[[4,1], [1,4], [2,1,2]]
Note that 5 is the distance, and 10, 4, 1, and 2 are the distances that a pogo stick may travel.
The issue is that these are not all the possible paths! For example, it is missing the paths such as [1, 1, 1, 1, 1] or [2, 2, 1].
Can anybody please help me modify my function to include these? I believe it is happening because once my loop finds the first occurrence of a pogo stick distance that's less than the remaining distance it will immediately use that path and ignore other possibilities.
for(int i = 0;i < pogoSticks.size();i++){
//part to calculate small enough
int[] temps = new int[pogoSticks.size];
int temp1 = 0;
for(int j; j< pogoStricks.size();i++){
if(pogoSticks.getIndex(j) + k <= totalDisatnce){
temps[temp1] = pogoSticks.getIndex(j);
}
//code to calculate number of paths to get to TotalDistance
This should do half the job, now you just need a method to calculate the distance from all the temps variables. I suggest you subtract each value from the TotalDistance and see which numbers added up would equal that.

How to perform a sum of an int[] array [duplicate]

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 5 years ago.
Given an array A of 10 ints, initialize a local variable called sum and use a loop to find the sum of all numbers in the array A.
This was my answer that I submitted:
sum = 0;
while( A, < 10) {
sum = sum += A;
}
I didn't get any points on this question. What did I do wrong?
Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();
Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
int i = 0; // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}
The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.
int sum=0;
for(int i:A)
sum+=i;
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
Here is an efficient way to solve this question using For loops in Java
public static void main(String[] args) {
int [] numbers = { 1, 2, 3, 4 };
int size = numbers.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
System.out.println(sum);
}

Categories

Resources