java - Standard Deviation -
hi have created code calculate standard deviation of set of numbers, here code below:
public class standarddev { public static void main(string[] args) { scanner in = new scanner(system.in); int n = in.nextint(); int[] arr = new int[n]; double sum = 0.0; for(int = 0; < n; i++) { arr[i] = in.nextint(); } arrays.sort(arr); double median = n % 2 != 0 ? arr[n/2] : (arr[n/2] + arr[(n/2)-1])/2; for(int = 0; < n; i++) { sum += math.pow(arr[i] - median,2); } system.out.printf("%.1f", math.sqrt(sum/n)); } }
however when input this:
10
64630 11735 14216 99233 14470 4978 73429 38120 51135 67060
i different result expected answer. output: 30475.6
expected output: 30466.9
but if tried input below correct answer:
5
10 40 30 50 20
my output: 14.1
expected output: 14.1
rewrote code calculate standard deviation, based on mean:
import java.util.*; import java.lang.*; import java.io.*; class standarddev { public static void main(string[] args) { scanner in = new scanner(system.in); int n = in.nextint(); int[] arr = new int[n]; double sum = 0.0; double mean = 0; for(int = 0; < n; i++) { arr[i] = in.nextint(); mean += arr[i]; } mean /= n; for(int = 0; < n; i++) { sum += math.pow(arr[i] - mean,2); } system.out.printf("%.1f", math.sqrt(sum/n)); } }
example: http://ideone.com/qy1wkw
Comments
Post a Comment