~ubuntu-branches/ubuntu/oneiric/commons-math/oneiric

« back to all changes in this revision

Viewing changes to src/main/java/org/apache/commons/math/util/MathUtils.java

  • Committer: Bazaar Package Importer
  • Author(s): Damien Raude-Morvan
  • Date: 2010-04-05 23:33:02 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20100405233302-gpqlceked76nw28a
Tags: 2.1-1
* New upstream release.
* Bump Standards-Version to 3.8.4: no changes needed
* Bump debhelper to >= 7
* Switch to 3.0 (quilt) source format:
  - Remove B-D on quilt
  - Add d/source/format
  - Remove d/README.source

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
 
26
26
/**
27
27
 * Some useful additions to the built-in functions in {@link Math}.
28
 
 * @version $Revision: 772119 $ $Date: 2009-05-06 05:43:28 -0400 (Wed, 06 May 2009) $
 
28
 * @version $Revision: 927249 $ $Date: 2010-03-24 21:06:51 -0400 (Wed, 24 Mar 2010) $
29
29
 */
30
30
public final class MathUtils {
31
31
 
38
38
     */
39
39
    public static final double SAFE_MIN = 0x1.0p-1022;
40
40
 
 
41
    /**
 
42
     * 2 π.
 
43
     * @since 2.1
 
44
     */
 
45
    public static final double TWO_PI = 2 * Math.PI;
 
46
 
41
47
    /** -1.0 cast as a byte. */
42
48
    private static final byte  NB = (byte)-1;
43
49
 
56
62
    /** 0.0 cast as a short. */
57
63
    private static final short ZS = (short)0;
58
64
 
59
 
    /** 2 π. */
60
 
    private static final double TWO_PI = 2 * Math.PI;
61
 
 
62
65
    /** Gap between NaN and regular numbers. */
63
66
    private static final int NAN_GAP = 4 * 1024 * 1024;
64
67
 
65
68
    /** Offset to order signed double numbers lexicographically. */
66
69
    private static final long SGN_MASK = 0x8000000000000000L;
67
70
 
 
71
    /** All long-representable factorials */
 
72
    private static final long[] FACTORIALS = new long[] {
 
73
                       1l,                  1l,                   2l,
 
74
                       6l,                 24l,                 120l,
 
75
                     720l,               5040l,               40320l,
 
76
                  362880l,            3628800l,            39916800l,
 
77
               479001600l,         6227020800l,         87178291200l,
 
78
           1307674368000l,     20922789888000l,     355687428096000l,
 
79
        6402373705728000l, 121645100408832000l, 2432902008176640000l };
 
80
 
68
81
    /**
69
82
     * Private Constructor
70
83
     */
74
87
 
75
88
    /**
76
89
     * Add two integers, checking for overflow.
77
 
     * 
 
90
     *
78
91
     * @param x an addend
79
92
     * @param y an addend
80
93
     * @return the sum <code>x+y</code>
92
105
 
93
106
    /**
94
107
     * Add two long integers, checking for overflow.
95
 
     * 
 
108
     *
96
109
     * @param a an addend
97
110
     * @param b an addend
98
111
     * @return the sum <code>a+b</code>
103
116
    public static long addAndCheck(long a, long b) {
104
117
        return addAndCheck(a, b, "overflow: add");
105
118
    }
106
 
    
 
119
 
107
120
    /**
108
121
     * Add two long integers, checking for overflow.
109
 
     * 
 
122
     *
110
123
     * @param a an addend
111
124
     * @param b an addend
112
125
     * @param msg the message to use for any thrown exception.
122
135
            ret = addAndCheck(b, a, msg);
123
136
        } else {
124
137
            // assert a <= b
125
 
            
 
138
 
126
139
            if (a < 0) {
127
140
                if (b < 0) {
128
141
                    // check for negative overflow
149
162
        }
150
163
        return ret;
151
164
    }
152
 
    
 
165
 
153
166
    /**
154
167
     * Returns an exact representation of the <a
155
168
     * href="http://mathworld.wolfram.com/BinomialCoefficient.html"> Binomial
167
180
     * <code>Long.MAX_VALUE</code> an <code>ArithMeticException</code> is
168
181
     * thrown.</li>
169
182
     * </ul></p>
170
 
     * 
 
183
     *
171
184
     * @param n the size of the set
172
185
     * @param k the size of the subsets to be counted
173
186
     * @return <code>n choose k</code>
186
199
        // Use symmetry for large k
187
200
        if (k > n / 2)
188
201
            return binomialCoefficient(n, n - k);
189
 
        
 
202
 
190
203
        // We use the formula
191
204
        // (n choose k) = n! / (n-k)! / k!
192
205
        // (n choose k) == ((n-k+1)*...*n) / (1*...*k)
195
208
        long result = 1;
196
209
        if (n <= 61) {
197
210
            // For n <= 61, the naive implementation cannot overflow.
198
 
            for (int j = 1, i = n - k + 1; j <= k; i++, j++) {
 
211
            int i = n - k + 1;
 
212
            for (int j = 1; j <= k; j++) {
199
213
                result = result * i / j;
 
214
                i++;
200
215
            }
201
216
        } else if (n <= 66) {
202
217
            // For n > 61 but n <= 66, the result cannot overflow,
203
218
            // but we must take care not to overflow intermediate values.
204
 
            for (int j = 1, i = n - k + 1; j <= k; i++, j++) {
 
219
            int i = n - k + 1;
 
220
            for (int j = 1; j <= k; j++) {
205
221
                // We know that (result * i) is divisible by j,
206
222
                // but (result * i) may overflow, so we split j:
207
223
                // Filter out the gcd, d, so j/d and i/d are integer.
208
224
                // result is divisible by (j/d) because (j/d)
209
225
                // is relative prime to (i/d) and is a divisor of
210
226
                // result * (i/d).
211
 
                long d = gcd(i, j);
 
227
                final long d = gcd(i, j);
212
228
                result = (result / (j / d)) * (i / d);
 
229
                i++;
213
230
            }
214
231
        } else {
215
232
            // For n > 66, a result overflow might occur, so we check
216
233
            // the multiplication, taking care to not overflow
217
234
            // unnecessary.
218
 
            for (int j = 1, i = n - k + 1; j <= k; i++, j++) {
219
 
                long d = gcd(i, j);
220
 
                result = mulAndCheck((result / (j / d)), (i / d));
 
235
            int i = n - k + 1;
 
236
            for (int j = 1; j <= k; j++) {
 
237
                final long d = gcd(i, j);
 
238
                result = mulAndCheck(result / (j / d), i / d);
 
239
                i++;
221
240
            }
222
241
        }
223
242
        return result;
239
258
     * Double.MAX_VALUE is 1029. If the computed value exceeds Double.MAX_VALUE,
240
259
     * Double.POSITIVE_INFINITY is returned</li>
241
260
     * </ul></p>
242
 
     * 
 
261
     *
243
262
     * @param n the size of the set
244
263
     * @param k the size of the subsets to be counted
245
264
     * @return <code>n choose k</code>
259
278
        if (n < 67) {
260
279
            return binomialCoefficient(n,k);
261
280
        }
262
 
        
 
281
 
263
282
        double result = 1d;
264
283
        for (int i = 1; i <= k; i++) {
265
284
             result *= (double)(n - k + i) / (double)i;
266
285
        }
267
 
  
 
286
 
268
287
        return Math.floor(result + 0.5);
269
288
    }
270
 
    
 
289
 
271
290
    /**
272
291
     * Returns the natural <code>log</code> of the <a
273
292
     * href="http://mathworld.wolfram.com/BinomialCoefficient.html"> Binomial
280
299
     * <li> <code>0 <= k <= n </code> (otherwise
281
300
     * <code>IllegalArgumentException</code> is thrown)</li>
282
301
     * </ul></p>
283
 
     * 
 
302
     *
284
303
     * @param n the size of the set
285
304
     * @param k the size of the subsets to be counted
286
305
     * @return <code>n choose k</code>
294
313
        if ((k == 1) || (k == n - 1)) {
295
314
            return Math.log(n);
296
315
        }
297
 
        
 
316
 
298
317
        /*
299
318
         * For values small enough to do exact integer computation,
300
 
         * return the log of the exact value 
 
319
         * return the log of the exact value
301
320
         */
302
 
        if (n < 67) {  
 
321
        if (n < 67) {
303
322
            return Math.log(binomialCoefficient(n,k));
304
323
        }
305
 
        
 
324
 
306
325
        /*
307
326
         * Return the log of binomialCoefficientDouble for values that will not
308
327
         * overflow binomialCoefficientDouble
309
328
         */
310
 
        if (n < 1030) { 
 
329
        if (n < 1030) {
311
330
            return Math.log(binomialCoefficientDouble(n, k));
312
 
        } 
 
331
        }
313
332
 
314
333
        if (k > n / 2) {
315
334
            return binomialCoefficientLog(n, n - k);
330
349
            logSum -= Math.log(i);
331
350
        }
332
351
 
333
 
        return logSum;      
 
352
        return logSum;
334
353
    }
335
354
 
336
355
    /**
352
371
                  n);
353
372
        }
354
373
    }
355
 
    
 
374
 
356
375
    /**
357
376
     * Compares two numbers given some amount of allowed error.
358
 
     * 
 
377
     *
359
378
     * @param x the first number
360
379
     * @param y the second number
361
380
     * @param eps the amount of error to allow when checking for equality
371
390
        }
372
391
        return 1;
373
392
    }
374
 
    
 
393
 
375
394
    /**
376
395
     * Returns the <a href="http://mathworld.wolfram.com/HyperbolicCosine.html">
377
396
     * hyperbolic cosine</a> of x.
378
 
     * 
 
397
     *
379
398
     * @param x double value for which to find the hyperbolic cosine
380
399
     * @return hyperbolic cosine of x
381
400
     */
382
401
    public static double cosh(double x) {
383
402
        return (Math.exp(x) + Math.exp(-x)) / 2.0;
384
403
    }
385
 
    
 
404
 
386
405
    /**
387
406
     * Returns true iff both arguments are NaN or neither is NaN and they are
388
407
     * equal
389
 
     * 
 
408
     *
390
409
     * @param x first value
391
410
     * @param y second value
392
411
     * @return true if the values are equal or both are NaN
393
412
     */
394
413
    public static boolean equals(double x, double y) {
395
 
        return ((Double.isNaN(x) && Double.isNaN(y)) || x == y);
 
414
        return (Double.isNaN(x) && Double.isNaN(y)) || x == y;
396
415
    }
397
416
 
398
417
    /**
401
420
     * <p>
402
421
     * Two NaNs are considered equals, as are two infinities with same sign.
403
422
     * </p>
404
 
     * 
 
423
     *
405
424
     * @param x first value
406
425
     * @param y second value
407
426
     * @param eps the amount of absolute error to allow
410
429
    public static boolean equals(double x, double y, double eps) {
411
430
      return equals(x, y) || (Math.abs(y - x) <= eps);
412
431
    }
413
 
    
 
432
 
414
433
    /**
415
434
     * Returns true iff both arguments are equal or within the range of allowed
416
435
     * error (inclusive).
447
466
    /**
448
467
     * Returns true iff both arguments are null or have same dimensions
449
468
     * and all their elements are {@link #equals(double,double) equals}
450
 
     * 
 
469
     *
451
470
     * @param x first array
452
471
     * @param y second array
453
472
     * @return true if the values are both null or have same dimension
468
487
        }
469
488
        return true;
470
489
    }
471
 
    
472
 
    /** All long-representable factorials */
473
 
    private static final long[] factorials = new long[] 
474
 
       {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800,
475
 
        479001600, 6227020800l, 87178291200l, 1307674368000l, 20922789888000l,
476
 
        355687428096000l, 6402373705728000l, 121645100408832000l,
477
 
        2432902008176640000l};
478
490
 
479
491
    /**
480
492
     * Returns n!. Shorthand for <code>n</code> <a
491
503
     * an <code>ArithMeticException </code> is thrown.</li>
492
504
     * </ul>
493
505
     * </p>
494
 
     * 
 
506
     *
495
507
     * @param n argument
496
508
     * @return <code>n!</code>
497
509
     * @throws ArithmeticException if the result is too large to be represented
508
520
            throw new ArithmeticException(
509
521
                    "factorial value is too large to fit in a long");
510
522
        }
511
 
        return factorials[n];
 
523
        return FACTORIALS[n];
512
524
    }
513
525
 
514
526
    /**
526
538
     * Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned</li>
527
539
     * </ul>
528
540
     * </p>
529
 
     * 
 
541
     *
530
542
     * @param n argument
531
543
     * @return <code>n!</code>
532
544
     * @throws IllegalArgumentException if n < 0
551
563
     * <li> <code>n >= 0</code> (otherwise
552
564
     * <code>IllegalArgumentException</code> is thrown)</li>
553
565
     * </ul></p>
554
 
     * 
 
566
     *
555
567
     * @param n argument
556
568
     * @return <code>n!</code>
557
569
     * @throws IllegalArgumentException if preconditions are not met.
593
605
     * <li>The invocation <code>gcd(0, 0)</code> is the only one which returns
594
606
     * <code>0</code>.</li>
595
607
     * </ul>
596
 
     * 
 
608
     *
597
609
     * @param p any number
598
610
     * @param q any number
599
611
     * @return the greatest common divisor, never negative
600
 
     * @throws ArithmeticException
601
 
     *             if the result cannot be represented as a nonnegative int
602
 
     *             value
 
612
     * @throws ArithmeticException if the result cannot be represented as a
 
613
     * nonnegative int value
603
614
     * @since 1.1
604
615
     */
605
616
    public static int gcd(final int p, final int q) {
611
622
                        "overflow: gcd({0}, {1}) is 2^31",
612
623
                        p, q);
613
624
            }
614
 
            return (Math.abs(u) + Math.abs(v));
 
625
            return Math.abs(u) + Math.abs(v);
615
626
        }
616
627
        // keep u and v negative, as negative integers range down to
617
628
        // -2^31, while positive numbers can only be as large as 2^31-1
663
674
    }
664
675
 
665
676
    /**
 
677
     * <p>
 
678
     * Gets the greatest common divisor of the absolute value of two numbers,
 
679
     * using the "binary gcd" method which avoids division and modulo
 
680
     * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 
681
     * Stein (1961).
 
682
     * </p>
 
683
     * Special cases:
 
684
     * <ul>
 
685
     * <li>The invocations
 
686
     * <code>gcd(Long.MIN_VALUE, Long.MIN_VALUE)</code>,
 
687
     * <code>gcd(Long.MIN_VALUE, 0L)</code> and
 
688
     * <code>gcd(0L, Long.MIN_VALUE)</code> throw an
 
689
     * <code>ArithmeticException</code>, because the result would be 2^63, which
 
690
     * is too large for a long value.</li>
 
691
     * <li>The result of <code>gcd(x, x)</code>, <code>gcd(0L, x)</code> and
 
692
     * <code>gcd(x, 0L)</code> is the absolute value of <code>x</code>, except
 
693
     * for the special cases above.
 
694
     * <li>The invocation <code>gcd(0L, 0L)</code> is the only one which returns
 
695
     * <code>0L</code>.</li>
 
696
     * </ul>
 
697
     *
 
698
     * @param p any number
 
699
     * @param q any number
 
700
     * @return the greatest common divisor, never negative
 
701
     * @throws ArithmeticException if the result cannot be represented as a nonnegative long
 
702
     * value
 
703
     * @since 2.1
 
704
     */
 
705
    public static long gcd(final long p, final long q) {
 
706
        long u = p;
 
707
        long v = q;
 
708
        if ((u == 0) || (v == 0)) {
 
709
            if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){
 
710
                throw MathRuntimeException.createArithmeticException(
 
711
                        "overflow: gcd({0}, {1}) is 2^63",
 
712
                        p, q);
 
713
            }
 
714
            return Math.abs(u) + Math.abs(v);
 
715
        }
 
716
        // keep u and v negative, as negative integers range down to
 
717
        // -2^63, while positive numbers can only be as large as 2^63-1
 
718
        // (i.e. we can't necessarily negate a negative number without
 
719
        // overflow)
 
720
        /* assert u!=0 && v!=0; */
 
721
        if (u > 0) {
 
722
            u = -u;
 
723
        } // make u negative
 
724
        if (v > 0) {
 
725
            v = -v;
 
726
        } // make v negative
 
727
        // B1. [Find power of 2]
 
728
        int k = 0;
 
729
        while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are
 
730
                                                            // both even...
 
731
            u /= 2;
 
732
            v /= 2;
 
733
            k++; // cast out twos.
 
734
        }
 
735
        if (k == 63) {
 
736
            throw MathRuntimeException.createArithmeticException(
 
737
                    "overflow: gcd({0}, {1}) is 2^63",
 
738
                    p, q);
 
739
        }
 
740
        // B2. Initialize: u and v have been divided by 2^k and at least
 
741
        // one is odd.
 
742
        long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
 
743
        // t negative: u was odd, v may be even (t replaces v)
 
744
        // t positive: u was even, v is odd (t replaces u)
 
745
        do {
 
746
            /* assert u<0 && v<0; */
 
747
            // B4/B3: cast out twos from t.
 
748
            while ((t & 1) == 0) { // while t is even..
 
749
                t /= 2; // cast out twos
 
750
            }
 
751
            // B5 [reset max(u,v)]
 
752
            if (t > 0) {
 
753
                u = -t;
 
754
            } else {
 
755
                v = t;
 
756
            }
 
757
            // B6/B3. at this point both u and v should be odd.
 
758
            t = (v - u) / 2;
 
759
            // |u| larger: t positive (replace u)
 
760
            // |v| larger: t negative (replace v)
 
761
        } while (t != 0);
 
762
        return -u * (1L << k); // gcd is u*2^k
 
763
    }
 
764
 
 
765
    /**
666
766
     * Returns an integer hash code representing the given double value.
667
 
     * 
 
767
     *
668
768
     * @param value the value to be hashed
669
769
     * @return the hash code
670
770
     */
674
774
 
675
775
    /**
676
776
     * Returns an integer hash code representing the given double array.
677
 
     * 
 
777
     *
678
778
     * @param value the value to be hashed (may be null)
679
779
     * @return the hash code
680
780
     * @since 1.2
686
786
    /**
687
787
     * For a byte value x, this method returns (byte)(+1) if x >= 0 and
688
788
     * (byte)(-1) if x < 0.
689
 
     * 
 
789
     *
690
790
     * @param x the value, a byte
691
791
     * @return (byte)(+1) or (byte)(-1), depending on the sign of x
692
792
     */
698
798
     * For a double precision value x, this method returns +1.0 if x >= 0 and
699
799
     * -1.0 if x < 0. Returns <code>NaN</code> if <code>x</code> is
700
800
     * <code>NaN</code>.
701
 
     * 
 
801
     *
702
802
     * @param x the value, a double
703
803
     * @return +1.0 or -1.0, depending on the sign of x
704
804
     */
712
812
    /**
713
813
     * For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x <
714
814
     * 0. Returns <code>NaN</code> if <code>x</code> is <code>NaN</code>.
715
 
     * 
 
815
     *
716
816
     * @param x the value, a float
717
817
     * @return +1.0F or -1.0F, depending on the sign of x
718
818
     */
725
825
 
726
826
    /**
727
827
     * For an int value x, this method returns +1 if x >= 0 and -1 if x < 0.
728
 
     * 
 
828
     *
729
829
     * @param x the value, an int
730
830
     * @return +1 or -1, depending on the sign of x
731
831
     */
735
835
 
736
836
    /**
737
837
     * For a long value x, this method returns +1L if x >= 0 and -1L if x < 0.
738
 
     * 
 
838
     *
739
839
     * @param x the value, a long
740
840
     * @return +1L or -1L, depending on the sign of x
741
841
     */
746
846
    /**
747
847
     * For a short value x, this method returns (short)(+1) if x >= 0 and
748
848
     * (short)(-1) if x < 0.
749
 
     * 
 
849
     *
750
850
     * @param x the value, a short
751
851
     * @return (short)(+1) or (short)(-1), depending on the sign of x
752
852
     */
768
868
     * <li>The result of <code>lcm(0, x)</code> and <code>lcm(x, 0)</code> is
769
869
     * <code>0</code> for any <code>x</code>.
770
870
     * </ul>
771
 
     * 
 
871
     *
772
872
     * @param a any number
773
873
     * @param b any number
774
874
     * @return the least common multiple, never negative
782
882
            return 0;
783
883
        }
784
884
        int lcm = Math.abs(mulAndCheck(a / gcd(a, b), b));
785
 
        if (lcm == Integer.MIN_VALUE){
786
 
            throw new ArithmeticException("overflow: lcm is 2^31");
787
 
        }
788
 
        return lcm;
789
 
    }
790
 
 
791
 
    /** 
792
 
     * <p>Returns the 
 
885
        if (lcm == Integer.MIN_VALUE) {
 
886
            throw MathRuntimeException.createArithmeticException(
 
887
                "overflow: lcm({0}, {1}) is 2^31",
 
888
                a, b);
 
889
        }
 
890
        return lcm;
 
891
    }
 
892
 
 
893
    /**
 
894
     * <p>
 
895
     * Returns the least common multiple of the absolute value of two numbers,
 
896
     * using the formula <code>lcm(a,b) = (a / gcd(a,b)) * b</code>.
 
897
     * </p>
 
898
     * Special cases:
 
899
     * <ul>
 
900
     * <li>The invocations <code>lcm(Long.MIN_VALUE, n)</code> and
 
901
     * <code>lcm(n, Long.MIN_VALUE)</code>, where <code>abs(n)</code> is a
 
902
     * power of 2, throw an <code>ArithmeticException</code>, because the result
 
903
     * would be 2^63, which is too large for an int value.</li>
 
904
     * <li>The result of <code>lcm(0L, x)</code> and <code>lcm(x, 0L)</code> is
 
905
     * <code>0L</code> for any <code>x</code>.
 
906
     * </ul>
 
907
     *
 
908
     * @param a any number
 
909
     * @param b any number
 
910
     * @return the least common multiple, never negative
 
911
     * @throws ArithmeticException if the result cannot be represented as a nonnegative long
 
912
     * value
 
913
     * @since 2.1
 
914
     */
 
915
    public static long lcm(long a, long b) {
 
916
        if (a==0 || b==0){
 
917
            return 0;
 
918
        }
 
919
        long lcm = Math.abs(mulAndCheck(a / gcd(a, b), b));
 
920
        if (lcm == Long.MIN_VALUE){
 
921
            throw MathRuntimeException.createArithmeticException(
 
922
                "overflow: lcm({0}, {1}) is 2^63",
 
923
                a, b);
 
924
        }
 
925
        return lcm;
 
926
    }
 
927
 
 
928
    /**
 
929
     * <p>Returns the
793
930
     * <a href="http://mathworld.wolfram.com/Logarithm.html">logarithm</a>
794
931
     * for base <code>b</code> of <code>x</code>.
795
932
     * </p>
796
 
     * <p>Returns <code>NaN<code> if either argument is negative.  If 
 
933
     * <p>Returns <code>NaN<code> if either argument is negative.  If
797
934
     * <code>base</code> is 0 and <code>x</code> is positive, 0 is returned.
798
 
     * If <code>base</code> is positive and <code>x</code> is 0, 
 
935
     * If <code>base</code> is positive and <code>x</code> is 0,
799
936
     * <code>Double.NEGATIVE_INFINITY</code> is returned.  If both arguments
800
937
     * are 0, the result is <code>NaN</code>.</p>
801
 
     * 
 
938
     *
802
939
     * @param base the base of the logarithm, must be greater than 0
803
940
     * @param x argument, must be greater than 0
804
941
     * @return the value of the logarithm - the number y such that base^y = x.
805
942
     * @since 1.2
806
 
     */ 
 
943
     */
807
944
    public static double log(double base, double x) {
808
945
        return Math.log(x)/Math.log(base);
809
946
    }
810
947
 
811
948
    /**
812
949
     * Multiply two integers, checking for overflow.
813
 
     * 
 
950
     *
814
951
     * @param x a factor
815
952
     * @param y a factor
816
953
     * @return the product <code>x*y</code>
828
965
 
829
966
    /**
830
967
     * Multiply two long integers, checking for overflow.
831
 
     * 
 
968
     *
832
969
     * @param a first value
833
970
     * @param b second value
834
971
     * @return the product <code>a * b</code>
857
994
                        ret = a * b;
858
995
                    } else {
859
996
                        throw new ArithmeticException(msg);
860
 
                        
 
997
 
861
998
                    }
862
999
                } else {
863
1000
                    // assert b == 0
866
1003
            } else if (a > 0) {
867
1004
                // assert a > 0
868
1005
                // assert b > 0
869
 
                
 
1006
 
870
1007
                // check for positive overflow with positive a, positive b
871
1008
                if (a <= Long.MAX_VALUE / b) {
872
1009
                    ret = a * b;
891
1028
     * strictly less than <code>d</code> is returned.</p>
892
1029
     * <p>
893
1030
     * If <code>d</code> is NaN or Infinite, it is returned unchanged.</p>
894
 
     * 
 
1031
     *
895
1032
     * @param d base number
896
1033
     * @param direction (the only important thing is whether
897
1034
     * direction is greater or smaller than d)
941
1078
    /**
942
1079
     * Scale a number by 2<sup>scaleFactor</sup>.
943
1080
     * <p>If <code>d</code> is 0 or NaN or Infinite, it is returned unchanged.</p>
944
 
     * 
 
1081
     *
945
1082
     * @param d base number
946
1083
     * @param scaleFactor power of two by which d sould be multiplied
947
1084
     * @return d &times; 2<sup>scaleFactor</sup>
988
1125
         return a - TWO_PI * Math.floor((a + Math.PI - center) / TWO_PI);
989
1126
     }
990
1127
 
 
1128
     /**
 
1129
      * <p>Normalizes an array to make it sum to a specified value.
 
1130
      * Returns the result of the transformation <pre>
 
1131
      *    x |-> x * normalizedSum / sum
 
1132
      * </pre>
 
1133
      * applied to each non-NaN element x of the input array, where sum is the
 
1134
      * sum of the non-NaN entries in the input array.</p>
 
1135
      *
 
1136
      * <p>Throws IllegalArgumentException if <code>normalizedSum</code> is infinite
 
1137
      * or NaN and ArithmeticException if the input array contains any infinite elements
 
1138
      * or sums to 0</p>
 
1139
      *
 
1140
      * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 
1141
      *
 
1142
      * @param values input array to be normalized
 
1143
      * @param normalizedSum target sum for the normalized array
 
1144
      * @return normalized array
 
1145
      * @throws ArithmeticException if the input array contains infinite elements or sums to zero
 
1146
      * @throws IllegalArgumentException if the target sum is infinite or NaN
 
1147
      * @since 2.1
 
1148
      */
 
1149
     public static double[] normalizeArray(double[] values, double normalizedSum)
 
1150
       throws ArithmeticException, IllegalArgumentException {
 
1151
         if (Double.isInfinite(normalizedSum)) {
 
1152
             throw MathRuntimeException.createIllegalArgumentException(
 
1153
                     "Cannot normalize to an infinite value");
 
1154
         }
 
1155
         if (Double.isNaN(normalizedSum)) {
 
1156
             throw MathRuntimeException.createIllegalArgumentException(
 
1157
                     "Cannot normalize to NaN");
 
1158
         }
 
1159
         double sum = 0d;
 
1160
         final int len = values.length;
 
1161
         double[] out = new double[len];
 
1162
         for (int i = 0; i < len; i++) {
 
1163
             if (Double.isInfinite(values[i])) {
 
1164
                 throw MathRuntimeException.createArithmeticException(
 
1165
                         "Array contains an infinite element, {0} at index {1}", values[i], i);
 
1166
             }
 
1167
             if (!Double.isNaN(values[i])) {
 
1168
                 sum += values[i];
 
1169
             }
 
1170
         }
 
1171
         if (sum == 0) {
 
1172
             throw MathRuntimeException.createArithmeticException(
 
1173
                     "Array sums to zero");
 
1174
         }
 
1175
         for (int i = 0; i < len; i++) {
 
1176
             if (Double.isNaN(values[i])) {
 
1177
                 out[i] = Double.NaN;
 
1178
             } else {
 
1179
                 out[i] = values[i] * normalizedSum / sum;
 
1180
             }
 
1181
         }
 
1182
         return out;
 
1183
     }
 
1184
 
991
1185
    /**
992
1186
     * Round the given value to the specified number of decimal places. The
993
1187
     * value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method.
994
 
     * 
 
1188
     *
995
1189
     * @param x the value to round.
996
1190
     * @param scale the number of digits to the right of the decimal point.
997
1191
     * @return the rounded value.
1005
1199
     * Round the given value to the specified number of decimal places. The
1006
1200
     * value is rounded using the given method which is any method defined in
1007
1201
     * {@link BigDecimal}.
1008
 
     * 
 
1202
     *
1009
1203
     * @param x the value to round.
1010
1204
     * @param scale the number of digits to the right of the decimal point.
1011
1205
     * @param roundingMethod the rounding method as defined in
1021
1215
                   .doubleValue();
1022
1216
        } catch (NumberFormatException ex) {
1023
1217
            if (Double.isInfinite(x)) {
1024
 
                return x;          
 
1218
                return x;
1025
1219
            } else {
1026
1220
                return Double.NaN;
1027
1221
            }
1031
1225
    /**
1032
1226
     * Round the given value to the specified number of decimal places. The
1033
1227
     * value is rounding using the {@link BigDecimal#ROUND_HALF_UP} method.
1034
 
     * 
 
1228
     *
1035
1229
     * @param x the value to round.
1036
1230
     * @param scale the number of digits to the right of the decimal point.
1037
1231
     * @return the rounded value.
1045
1239
     * Round the given value to the specified number of decimal places. The
1046
1240
     * value is rounded using the given method which is any method defined in
1047
1241
     * {@link BigDecimal}.
1048
 
     * 
 
1242
     *
1049
1243
     * @param x the value to round.
1050
1244
     * @param scale the number of digits to the right of the decimal point.
1051
1245
     * @param roundingMethod the rounding method as defined in
1063
1257
     * Round the given non-negative, value to the "nearest" integer. Nearest is
1064
1258
     * determined by the rounding method specified. Rounding methods are defined
1065
1259
     * in {@link BigDecimal}.
1066
 
     * 
 
1260
     *
1067
1261
     * @param unscaled the value to round.
1068
1262
     * @param sign the sign of the original, scaled value.
1069
1263
     * @param roundingMethod the rounding method as defined in
1159
1353
     * <p>
1160
1354
     * For a byte value x, this method returns (byte)(+1) if x > 0, (byte)(0) if
1161
1355
     * x = 0, and (byte)(-1) if x < 0.</p>
1162
 
     * 
 
1356
     *
1163
1357
     * @param x the value, a byte
1164
1358
     * @return (byte)(+1), (byte)(0), or (byte)(-1), depending on the sign of x
1165
1359
     */
1175
1369
     * <code>+1.0</code> if <code>x > 0</code>, <code>0.0</code> if
1176
1370
     * <code>x = 0.0</code>, and <code>-1.0</code> if <code>x < 0</code>.
1177
1371
     * Returns <code>NaN</code> if <code>x</code> is <code>NaN</code>.</p>
1178
 
     * 
 
1372
     *
1179
1373
     * @param x the value, a double
1180
1374
     * @return +1.0, 0.0, or -1.0, depending on the sign of x
1181
1375
     */
1193
1387
     * For a float value x, this method returns +1.0F if x > 0, 0.0F if x =
1194
1388
     * 0.0F, and -1.0F if x < 0. Returns <code>NaN</code> if <code>x</code>
1195
1389
     * is <code>NaN</code>.</p>
1196
 
     * 
 
1390
     *
1197
1391
     * @param x the value, a float
1198
1392
     * @return +1.0F, 0.0F, or -1.0F, depending on the sign of x
1199
1393
     */
1210
1404
     * <p>
1211
1405
     * For an int value x, this method returns +1 if x > 0, 0 if x = 0, and -1
1212
1406
     * if x < 0.</p>
1213
 
     * 
 
1407
     *
1214
1408
     * @param x the value, an int
1215
1409
     * @return +1, 0, or -1, depending on the sign of x
1216
1410
     */
1224
1418
     * <p>
1225
1419
     * For a long value x, this method returns +1L if x > 0, 0L if x = 0, and
1226
1420
     * -1L if x < 0.</p>
1227
 
     * 
 
1421
     *
1228
1422
     * @param x the value, a long
1229
1423
     * @return +1L, 0L, or -1L, depending on the sign of x
1230
1424
     */
1238
1432
     * <p>
1239
1433
     * For a short value x, this method returns (short)(+1) if x > 0, (short)(0)
1240
1434
     * if x = 0, and (short)(-1) if x < 0.</p>
1241
 
     * 
 
1435
     *
1242
1436
     * @param x the value, a short
1243
1437
     * @return (short)(+1), (short)(0), or (short)(-1), depending on the sign of
1244
1438
     *         x
1250
1444
    /**
1251
1445
     * Returns the <a href="http://mathworld.wolfram.com/HyperbolicSine.html">
1252
1446
     * hyperbolic sine</a> of x.
1253
 
     * 
 
1447
     *
1254
1448
     * @param x double value for which to find the hyperbolic sine
1255
1449
     * @return hyperbolic sine of x
1256
1450
     */
1260
1454
 
1261
1455
    /**
1262
1456
     * Subtract two integers, checking for overflow.
1263
 
     * 
 
1457
     *
1264
1458
     * @param x the minuend
1265
1459
     * @param y the subtrahend
1266
1460
     * @return the difference <code>x-y</code>
1278
1472
 
1279
1473
    /**
1280
1474
     * Subtract two long integers, checking for overflow.
1281
 
     * 
 
1475
     *
1282
1476
     * @param a first value
1283
1477
     * @param b second value
1284
1478
     * @return the difference <code>a-b</code>
1509
1703
     * @param p2 the second point
1510
1704
     * @return the L<sub>1</sub> distance between the two points
1511
1705
     */
1512
 
    public static final double distance1(double[] p1, double[] p2) {
 
1706
    public static double distance1(double[] p1, double[] p2) {
1513
1707
        double sum = 0;
1514
1708
        for (int i = 0; i < p1.length; i++) {
1515
1709
            sum += Math.abs(p1[i] - p2[i]);
1516
1710
        }
1517
1711
        return sum;
1518
1712
    }
1519
 
    
 
1713
 
1520
1714
    /**
1521
1715
     * Calculates the L<sub>1</sub> (sum of abs) distance between two points.
1522
1716
     *
1524
1718
     * @param p2 the second point
1525
1719
     * @return the L<sub>1</sub> distance between the two points
1526
1720
     */
1527
 
    public static final int distance1(int[] p1, int[] p2) {
 
1721
    public static int distance1(int[] p1, int[] p2) {
1528
1722
      int sum = 0;
1529
1723
      for (int i = 0; i < p1.length; i++) {
1530
1724
          sum += Math.abs(p1[i] - p2[i]);
1539
1733
     * @param p2 the second point
1540
1734
     * @return the L<sub>2</sub> distance between the two points
1541
1735
     */
1542
 
    public static final double distance(double[] p1, double[] p2) {
 
1736
    public static double distance(double[] p1, double[] p2) {
1543
1737
        double sum = 0;
1544
1738
        for (int i = 0; i < p1.length; i++) {
1545
1739
            final double dp = p1[i] - p2[i];
1547
1741
        }
1548
1742
        return Math.sqrt(sum);
1549
1743
    }
1550
 
    
 
1744
 
1551
1745
    /**
1552
1746
     * Calculates the L<sub>2</sub> (Euclidean) distance between two points.
1553
1747
     *
1555
1749
     * @param p2 the second point
1556
1750
     * @return the L<sub>2</sub> distance between the two points
1557
1751
     */
1558
 
    public static final double distance(int[] p1, int[] p2) {
1559
 
      int sum = 0;
 
1752
    public static double distance(int[] p1, int[] p2) {
 
1753
      double sum = 0;
1560
1754
      for (int i = 0; i < p1.length; i++) {
1561
 
          final int dp = p1[i] - p2[i];
 
1755
          final double dp = p1[i] - p2[i];
1562
1756
          sum += dp * dp;
1563
1757
      }
1564
1758
      return Math.sqrt(sum);
1565
1759
    }
1566
 
    
 
1760
 
1567
1761
    /**
1568
1762
     * Calculates the L<sub>&infin;</sub> (max of abs) distance between two points.
1569
1763
     *
1571
1765
     * @param p2 the second point
1572
1766
     * @return the L<sub>&infin;</sub> distance between the two points
1573
1767
     */
1574
 
    public static final double distanceInf(double[] p1, double[] p2) {
 
1768
    public static double distanceInf(double[] p1, double[] p2) {
1575
1769
        double max = 0;
1576
1770
        for (int i = 0; i < p1.length; i++) {
1577
1771
            max = Math.max(max, Math.abs(p1[i] - p2[i]));
1578
1772
        }
1579
1773
        return max;
1580
1774
    }
1581
 
    
 
1775
 
1582
1776
    /**
1583
1777
     * Calculates the L<sub>&infin;</sub> (max of abs) distance between two points.
1584
1778
     *
1586
1780
     * @param p2 the second point
1587
1781
     * @return the L<sub>&infin;</sub> distance between the two points
1588
1782
     */
1589
 
    public static final int distanceInf(int[] p1, int[] p2) {
 
1783
    public static int distanceInf(int[] p1, int[] p2) {
1590
1784
        int max = 0;
1591
1785
        for (int i = 0; i < p1.length; i++) {
1592
1786
            max = Math.max(max, Math.abs(p1[i] - p2[i]));
1594
1788
        return max;
1595
1789
    }
1596
1790
 
1597
 
    
 
1791
    /**
 
1792
     * Checks that the given array is sorted.
 
1793
     *
 
1794
     * @param val Values
 
1795
     * @param dir Order direction (-1 for decreasing, 1 for increasing)
 
1796
     * @param strict Whether the order should be strict
 
1797
     * @throws IllegalArgumentException if the array is not sorted.
 
1798
     */
 
1799
    public static void checkOrder(double[] val, int dir, boolean strict) {
 
1800
        double previous = val[0];
 
1801
 
 
1802
        int max = val.length;
 
1803
        for (int i = 1; i < max; i++) {
 
1804
            if (dir > 0) {
 
1805
                if (strict) {
 
1806
                    if (val[i] <= previous) {
 
1807
                        throw MathRuntimeException.createIllegalArgumentException("points {0} and {1} are not strictly increasing ({2} >= {3})",
 
1808
                                                                                  i - 1, i, previous, val[i]);
 
1809
                    }
 
1810
                } else {
 
1811
                    if (val[i] < previous) {
 
1812
                        throw MathRuntimeException.createIllegalArgumentException("points {0} and {1} are not increasing ({2} > {3})",
 
1813
                                                                                  i - 1, i, previous, val[i]);
 
1814
                    }
 
1815
                }
 
1816
            } else {
 
1817
                if (strict) {
 
1818
                    if (val[i] >= previous) {
 
1819
                        throw MathRuntimeException.createIllegalArgumentException("points {0} and {1} are not strictly decreasing ({2} <= {3})",
 
1820
                                                                                  i - 1, i, previous, val[i]);
 
1821
                    }
 
1822
                } else {
 
1823
                    if (val[i] > previous) {
 
1824
                        throw MathRuntimeException.createIllegalArgumentException("points {0} and {1} are not decreasing ({2} < {3})",
 
1825
                                                                                  i - 1, i, previous, val[i]);
 
1826
                    }
 
1827
                }
 
1828
            }
 
1829
 
 
1830
            previous = val[i];
 
1831
        }
 
1832
    }
1598
1833
}