File: Rational.java

package info (click to toggle)
libmetadata-extractor-java 2.6.4-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 4,124 kB
  • ctags: 2,408
  • sloc: java: 15,158; xml: 110; sh: 93; makefile: 18
file content (282 lines) | stat: -rw-r--r-- 9,872 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * Copyright 2002-2012 Drew Noakes
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 * More information about this project is available at:
 *
 *    http://drewnoakes.com/code/exif/
 *    http://code.google.com/p/metadata-extractor/
 */

package com.drew.lang;

import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;

import java.io.Serializable;

/**
 * Immutable class for holding a rational number without loss of precision.  Provides
 * a familiar representation via toString() in form <code>numerator/denominator</code>.
 *
 * @author Drew Noakes http://drewnoakes.com
 */
public class Rational extends java.lang.Number implements Serializable
{
    private static final long serialVersionUID = 510688928138848770L;

    /** Holds the numerator. */
    private final long _numerator;

    /** Holds the denominator. */
    private final long _denominator;

    /**
     * Creates a new instance of Rational.  Rational objects are immutable, so
     * once you've set your numerator and denominator values here, you're stuck
     * with them!
     */
    public Rational(long numerator, long denominator)
    {
        _numerator = numerator;
        _denominator = denominator;
    }

    /**
     * Returns the value of the specified number as a <code>double</code>.
     * This may involve rounding.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>double</code>.
     */
    public double doubleValue()
    {
        return (double) _numerator / (double) _denominator;
    }

    /**
     * Returns the value of the specified number as a <code>float</code>.
     * This may involve rounding.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>float</code>.
     */
    public float floatValue()
    {
        return (float) _numerator / (float) _denominator;
    }

    /**
     * Returns the value of the specified number as a <code>byte</code>.
     * This may involve rounding or truncation.  This implementation simply
     * casts the result of <code>doubleValue()</code> to <code>byte</code>.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>byte</code>.
     */
    public final byte byteValue()
    {
        return (byte) doubleValue();
    }

    /**
     * Returns the value of the specified number as an <code>int</code>.
     * This may involve rounding or truncation.  This implementation simply
     * casts the result of <code>doubleValue()</code> to <code>int</code>.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>int</code>.
     */
    public final int intValue()
    {
        return (int) doubleValue();
    }

    /**
     * Returns the value of the specified number as a <code>long</code>.
     * This may involve rounding or truncation.  This implementation simply
     * casts the result of <code>doubleValue()</code> to <code>long</code>.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>long</code>.
     */
    public final long longValue()
    {
        return (long) doubleValue();
    }

    /**
     * Returns the value of the specified number as a <code>short</code>.
     * This may involve rounding or truncation.  This implementation simply
     * casts the result of <code>doubleValue()</code> to <code>short</code>.
     *
     * @return the numeric value represented by this object after conversion
     *         to type <code>short</code>.
     */
    public final short shortValue()
    {
        return (short) doubleValue();
    }


    /** Returns the denominator. */
    public final long getDenominator()
    {
        return this._denominator;
    }

    /** Returns the numerator. */
    public final long getNumerator()
    {
        return this._numerator;
    }

    /**
     * Returns the reciprocal value of this object as a new Rational.
     *
     * @return the reciprocal in a new object
     */
    @NotNull
    public Rational getReciprocal()
    {
        return new Rational(this._denominator, this._numerator);
    }

    /** Checks if this rational number is an Integer, either positive or negative. */
    public boolean isInteger()
    {
        return _denominator == 1 ||
                (_denominator != 0 && (_numerator % _denominator == 0)) ||
                (_denominator == 0 && _numerator == 0);
    }

    /**
     * Returns a string representation of the object of form <code>numerator/denominator</code>.
     *
     * @return a string representation of the object.
     */
    @NotNull
    public String toString()
    {
        return _numerator + "/" + _denominator;
    }

    /** Returns the simplest representation of this Rational's value possible. */
    @NotNull
    public String toSimpleString(boolean allowDecimal)
    {
        if (_denominator == 0 && _numerator != 0) {
            return toString();
        } else if (isInteger()) {
            return Integer.toString(intValue());
        } else if (_numerator != 1 && _denominator % _numerator == 0) {
            // common factor between denominator and numerator
            long newDenominator = _denominator / _numerator;
            return new Rational(1, newDenominator).toSimpleString(allowDecimal);
        } else {
            Rational simplifiedInstance = getSimplifiedInstance();
            if (allowDecimal) {
                String doubleString = Double.toString(simplifiedInstance.doubleValue());
                if (doubleString.length() < 5) {
                    return doubleString;
                }
            }
            return simplifiedInstance.toString();
        }
    }

    /**
     * Decides whether a brute-force simplification calculation should be avoided
     * by comparing the maximum number of possible calculations with some threshold.
     *
     * @return true if the simplification should be performed, otherwise false
     */
    private boolean tooComplexForSimplification()
    {
        double maxPossibleCalculations = (((double) (Math.min(_denominator, _numerator) - 1) / 5d) + 2);
        final int maxSimplificationCalculations = 1000;
        return maxPossibleCalculations > maxSimplificationCalculations;
    }

    /**
     * Compares two <code>Rational</code> instances, returning true if they are mathematically
     * equivalent.
     *
     * @param obj the Rational to compare this instance to.
     * @return true if instances are mathematically equivalent, otherwise false.  Will also
     *         return false if <code>obj</code> is not an instance of <code>Rational</code>.
     */
    @Override
    public boolean equals(@Nullable Object obj)
    {
        if (obj==null || !(obj instanceof Rational))
            return false;
        Rational that = (Rational) obj;
        return this.doubleValue() == that.doubleValue();
    }

    @Override
    public int hashCode()
    {
        return (23 * (int)_denominator) + (int)_numerator;
    }

    /**
     * <p>
     * Simplifies the Rational number.</p>
     * <p>
     * Prime number series: 1, 2, 3, 5, 7, 9, 11, 13, 17</p>
     * <p>
     * To reduce a rational, need to see if both numerator and denominator are divisible
     * by a common factor.  Using the prime number series in ascending order guarantees
     * the minimum number of checks required.</p>
     * <p>
     * However, generating the prime number series seems to be a hefty task.  Perhaps
     * it's simpler to check if both d & n are divisible by all numbers from 2 ->
     * (Math.min(denominator, numerator) / 2).  In doing this, one can check for 2
     * and 5 once, then ignore all even numbers, and all numbers ending in 0 or 5.
     * This leaves four numbers from every ten to check.</p>
     * <p>
     * Therefore, the max number of pairs of modulus divisions required will be:</p>
     * <code><pre>
     *    4   Math.min(denominator, numerator) - 1
     *   -- * ------------------------------------ + 2
     *   10                    2
     * <p/>
     *   Math.min(denominator, numerator) - 1
     * = ------------------------------------ + 2
     *                  5
     * </pre></code>
     *
     * @return a simplified instance, or if the Rational could not be simplified,
     *         returns itself (unchanged)
     */
    @NotNull
    public Rational getSimplifiedInstance()
    {
        if (tooComplexForSimplification()) {
            return this;
        }
        for (int factor = 2; factor <= Math.min(_denominator, _numerator); factor++) {
            if ((factor % 2 == 0 && factor > 2) || (factor % 5 == 0 && factor > 5)) {
                continue;
            }
            if (_denominator % factor == 0 && _numerator % factor == 0) {
                // found a common factor
                return new Rational(_numerator / factor, _denominator / factor);
            }
        }
        return this;
    }
}