KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > tests > ArrayTest


1 package JSci.tests;
2
3 import java.util.Random JavaDoc;
4 import JSci.maths.*;
5
6 /**
7 * Testcase for array methods.
8 * @author Mark Hale
9 */

10 public class ArrayTest extends junit.framework.TestCase {
11         private final Random JavaDoc random = new Random JavaDoc();
12
13         public static void main(String JavaDoc arg[]) {
14                 junit.textui.TestRunner.run(ArrayTest.class);
15         }
16         public ArrayTest(String JavaDoc name) {
17                 super(name);
18         }
19         protected void setUp() {
20                 JSci.GlobalSettings.ZERO_TOL=1.0e-6;
21         }
22         public void testMedian() {
23                 final int N = random.nextInt(31)+1;
24                 double array[] = new double[N];
25                 array[0] = random.nextDouble();
26                 for(int i=1; i<N; i++) {
27                         array[i] = random.nextDouble();
28                         if(array[i] < array[i-1])
29                                 array[i]+=array[i-1];
30                 }
31                 double expected;
32                 if(isEven(N))
33                         expected = (array[N/2-1]+array[N/2])/2.0;
34                 else
35                         expected = array[N/2];
36                 randomize(array);
37                 double ans = ArrayMath.median(array);
38                 assertEquals("["+ArrayMath.toString(array)+"]", expected, ans, 0.0);
39         }
40         private static boolean isEven(int n) {
41                 return (n % 2 == 0);
42         }
43         private void randomize(double array[]) {
44                 for(int i=0; i<array.length; i++) {
45                         int p = random.nextInt(array.length);
46                         int q = random.nextInt(array.length);
47                         double tmp = array[q];
48                         array[q] = array[p];
49                         array[p] = tmp;
50                 }
51         }
52 }
53
54
Popular Tags