01: // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
02:
03: package jodd.util;
04:
05: /**
06: * Various math utilities.
07: */
08: public class MathUtil {
09:
10: /**
11: * Generates pseudo-random long from specific range. Generated number is
12: * great or equals to min parameter value and less then max parameter value.
13: * Uses {@link Math#random()}.
14: *
15: * @param min lower (inclusive) boundary
16: * @param max higher (exclusive) boundary
17: *
18: * @return pseudo-random value
19: */
20:
21: public static long randomLong(long min, long max) {
22: return min + (long) (Math.random() * (max - min));
23: }
24:
25: /**
26: * Generates pseudo-random integer from specific range. Generated number is
27: * great or equals to min parameter value and less then max parameter value.
28: * Uses {@link Math#random()}.
29: *
30: * @param min lower (inclusive) boundary
31: * @param max higher (exclusive) boundary
32: *
33: * @return pseudo-random value
34: */
35: public static int randomInt(int min, int max) {
36: return min + (int) (Math.random() * (max - min));
37: }
38:
39: // ---------------------------------------------------------------- compare
40:
41: /**
42: * Compares two doubles for order.
43: *
44: * @param lhs the first <code>double</code>
45: * @param rhs the second <code>double</code>
46: * @return <code>-1</code> if lhs is less, <code>+1</code> if greater,
47: * <code>0</code> if equal to rhs
48: */
49: public static int compare(double lhs, double rhs) {
50: if (lhs < rhs) {
51: return -1;
52: }
53: if (lhs > rhs) {
54: return +1;
55: }
56: long lhsBits = Double.doubleToLongBits(lhs);
57: long rhsBits = Double.doubleToLongBits(rhs);
58: if (lhsBits == rhsBits) {
59: return 0;
60: }
61: if (lhsBits < rhsBits) {
62: return -1;
63: } else {
64: return +1;
65: }
66: }
67:
68: /**
69: * Compares two floats for order.
70: *
71: * @param lhs the first <code>float</code>
72: * @param rhs the second <code>float</code>
73: * @return <code>-1</code> if lhs is less, <code>+1</code> if greater,
74: * <code>0</code> if equal to rhs
75: */
76: public static int compare(float lhs, float rhs) {
77: if (lhs < rhs) {
78: return -1;
79: }
80: if (lhs > rhs) {
81: return +1;
82: }
83: int lhsBits = Float.floatToIntBits(lhs);
84: int rhsBits = Float.floatToIntBits(rhs);
85: if (lhsBits == rhsBits) {
86: return 0;
87: }
88: if (lhsBits < rhsBits) {
89: return -1;
90: } else {
91: return +1;
92: }
93: }
94:
95: }
|