Debian Codegraph @

src/dr/math/BigDecimalUtils.java

raw symbols SCIP
1 /*
2 * BigDecimalUtils.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math;
27
28 import java.math.BigInteger;
29 import java.math.BigDecimal;
30
31 /**
32 * Several useful BigDecimal mathematical functions.
33 */
34 public class BigDecimalUtils {
35 /**
36 * Compute x^exponent to a given scale. Uses the same
37 * algorithm as class numbercruncher.mathutils.IntPower.
38 * @param x the value x
39 * @param exponent the exponent value
40 * @param scale the desired scale of the result
41 * @return the result value
42 */
43 public static BigDecimal intPower(BigDecimal x, long exponent,
44 int scale)
45 {
46 // If the exponent is negative, compute 1/(x^-exponent).
47 if (exponent < 0) {
48 return BigDecimal.valueOf(1)
49 .divide(intPower(x, -exponent, scale), scale,
50 BigDecimal.ROUND_HALF_EVEN);
51 }
52
53 BigDecimal power = BigDecimal.valueOf(1);
54
55 // Loop to compute value^exponent.
56 while (exponent > 0) {
57
58 // Is the rightmost bit a 1?
59 if ((exponent & 1) == 1) {
60 power = power.multiply(x)
61 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
62 }
63
64 // Square x and shift exponent 1 bit to the right.
65 x = x.multiply(x)
66 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
67 exponent >>= 1;
68
69 Thread.yield();
70 }
71
72 return power;
73 }
74
75 /**
76 * Compute the integral root of x to a given scale, x >= 0.
77 * Use Newton's algorithm.
78 * @param x the value of x
79 * @param index the integral root value
80 * @param scale the desired scale of the result
81 * @return the result value
82 */
83 public static BigDecimal intRoot(BigDecimal x, long index,
84 int scale)
85 {
86 // Check that x >= 0.
87 if (x.signum() < 0) {
88 throw new IllegalArgumentException("x < 0");
89 }
90
91 int sp1 = scale + 1;
92 BigDecimal n = x;
93 BigDecimal i = BigDecimal.valueOf(index);
94 BigDecimal im1 = BigDecimal.valueOf(index-1);
95 BigDecimal tolerance = BigDecimal.valueOf(5)
96 .movePointLeft(sp1);
97 BigDecimal xPrev;
98
99 // The initial approximation is x/index.
100 x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);
101
102 // Loop until the approximations converge
103 // (two successive approximations are equal after rounding).
104 do {
105 // x^(index-1)
106 BigDecimal xToIm1 = intPower(x, index-1, sp1);
107
108 // x^index
109 BigDecimal xToI =
110 x.multiply(xToIm1)
111 .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
112
113 // n + (index-1)*(x^index)
114 BigDecimal numerator =
115 n.add(im1.multiply(xToI))
116 .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
117
118 // (index*(x^(index-1))
119 BigDecimal denominator =
120 i.multiply(xToIm1)
121 .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
122
123 // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
124 xPrev = x;
125 x = numerator
126 .divide(denominator, sp1, BigDecimal.ROUND_DOWN);
127
128 Thread.yield();
129 } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);
130
131 return x;
132 }
133
134 /**
135 * Compute e^x to a given scale.
136 * Break x into its whole and fraction parts and
137 * compute (e^(1 + fraction/whole))^whole using Taylor's formula.
138 * @param x the value of x
139 * @param scale the desired scale of the result
140 * @return the result value
141 */
142 public static BigDecimal exp(BigDecimal x, int scale)
143 {
144 // e^0 = 1
145 if (x.signum() == 0) {
146 return BigDecimal.valueOf(1);
147 }
148
149 // If x is negative, return 1/(e^-x).
150 else if (x.signum() == -1) {
151 return BigDecimal.valueOf(1)
152 .divide(exp(x.negate(), scale), scale,
153 BigDecimal.ROUND_HALF_EVEN);
154 }
155
156 // Compute the whole part of x.
157 BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN);
158
159 // If there isn't a whole part, compute and return e^x.
160 if (xWhole.signum() == 0) return expTaylor(x, scale);
161
162 // Compute the fraction part of x.
163 BigDecimal xFraction = x.subtract(xWhole);
164
165 // z = 1 + fraction/whole
166 BigDecimal z = BigDecimal.valueOf(1)
167 .add(xFraction.divide(
168 xWhole, scale,
169 BigDecimal.ROUND_HALF_EVEN));
170
171 // t = e^z
172 BigDecimal t = expTaylor(z, scale);
173
174 BigDecimal maxLong = BigDecimal.valueOf(Long.MAX_VALUE);
175 BigDecimal result = BigDecimal.valueOf(1);
176
177 // Compute and return t^whole using intPower().
178 // If whole > Long.MAX_VALUE, then first compute products
179 // of e^Long.MAX_VALUE.
180 while (xWhole.compareTo(maxLong) >= 0) {
181 result = result.multiply(
182 intPower(t, Long.MAX_VALUE, scale))
183 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
184 xWhole = xWhole.subtract(maxLong);
185
186 Thread.yield();
187 }
188 return result.multiply(intPower(t, xWhole.longValue(), scale))
189 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
190 }
191
192 /**
193 * Compute e^x to a given scale by the Taylor series.
194 * @param x the value of x
195 * @param scale the desired scale of the result
196 * @return the result value
197 */
198 private static BigDecimal expTaylor(BigDecimal x, int scale)
199 {
200 BigDecimal factorial = BigDecimal.valueOf(1);
201 BigDecimal xPower = x;
202 BigDecimal sumPrev;
203
204 // 1 + x
205 BigDecimal sum = x.add(BigDecimal.valueOf(1));
206
207 // Loop until the sums converge
208 // (two successive sums are equal after rounding).
209 int i = 2;
210 do {
211 // x^i
212 xPower = xPower.multiply(x)
213 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
214
215 // i!
216 factorial = factorial.multiply(BigDecimal.valueOf(i));
217
218 // x^i/i!
219 BigDecimal term = xPower
220 .divide(factorial, scale,
221 BigDecimal.ROUND_HALF_EVEN);
222
223 // sum = sum + x^i/i!
224 sumPrev = sum;
225 sum = sum.add(term);
226
227 ++i;
228 Thread.yield();
229 } while (sum.compareTo(sumPrev) != 0);
230
231 return sum;
232 }
233
234 /**
235 * Compute the natural logarithm of x to a given scale, x > 0.
236 */
237 public static BigDecimal ln(BigDecimal x, int scale)
238 {
239 // Check that x > 0.
240 if (x.signum() <= 0) {
241 throw new IllegalArgumentException("x <= 0");
242 }
243
244 // The number of digits to the left of the decimal point.
245 int magnitude = x.toString().length() - x.scale() - 1;
246
247 if (magnitude < 3) {
248 return lnNewton(x, scale);
249 }
250
251 // Compute magnitude*ln(x^(1/magnitude)).
252 else {
253
254 // x^(1/magnitude)
255 BigDecimal root = intRoot(x, magnitude, scale);
256
257 // ln(x^(1/magnitude))
258 BigDecimal lnRoot = lnNewton(root, scale);
259
260 // magnitude*ln(x^(1/magnitude))
261 return BigDecimal.valueOf(magnitude).multiply(lnRoot)
262 .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
263 }
264 }
265
266 /**
267 * Compute the natural logarithm of x to a given scale, x > 0.
268 * Use Newton's algorithm.
269 */
270 private static BigDecimal lnNewton(BigDecimal x, int scale)
271 {
272 int sp1 = scale + 1;
273 BigDecimal n = x;
274 BigDecimal term;
275
276 // Convergence tolerance = 5*(10^-(scale+1))
277 BigDecimal tolerance = BigDecimal.valueOf(5)
278 .movePointLeft(sp1);
279
280 // Loop until the approximations converge
281 // (two successive approximations are within the tolerance).
282 do {
283
284 // e^x
285 BigDecimal eToX = exp(x, sp1);
286
287 // (e^x - n)/e^x
288 term = eToX.subtract(n)
289 .divide(eToX, sp1, BigDecimal.ROUND_DOWN);
290
291 // x - (e^x - n)/e^x
292 x = x.subtract(term);
293
294 Thread.yield();
295 } while (term.compareTo(tolerance) > 0);
296
297 return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
298 }
299
300 /**
301 * Compute the arctangent of x to a given scale, |x| < 1
302 * @param x the value of x
303 * @param scale the desired scale of the result
304 * @return the result value
305 */
306 public static BigDecimal arctan(BigDecimal x, int scale)
307 {
308 // Check that |x| < 1.
309 if (x.abs().compareTo(BigDecimal.valueOf(1)) >= 0) {
310 throw new IllegalArgumentException("|x| >= 1");
311 }
312
313 // If x is negative, return -arctan(-x).
314 if (x.signum() == -1) {
315 return arctan(x.negate(), scale).negate();
316 }
317 else {
318 return arctanTaylor(x, scale);
319 }
320 }
321
322 /**
323 * Compute the arctangent of x to a given scale
324 * by the Taylor series, |x| < 1
325 * @param x the value of x
326 * @param scale the desired scale of the result
327 * @return the result value
328 */
329 private static BigDecimal arctanTaylor(BigDecimal x, int scale)
330 {
331 int sp1 = scale + 1;
332 int i = 3;
333 boolean addFlag = false;
334
335 BigDecimal power = x;
336 BigDecimal sum = x;
337 BigDecimal term;
338
339 // Convergence tolerance = 5*(10^-(scale+1))
340 BigDecimal tolerance = BigDecimal.valueOf(5)
341 .movePointLeft(sp1);
342
343 // Loop until the approximations converge
344 // (two successive approximations are within the tolerance).
345 do {
346 // x^i
347 power = power.multiply(x).multiply(x)
348 .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
349
350 // (x^i)/i
351 term = power.divide(BigDecimal.valueOf(i), sp1,
352 BigDecimal.ROUND_HALF_EVEN);
353
354 // sum = sum +- (x^i)/i
355 sum = addFlag ? sum.add(term)
356 : sum.subtract(term);
357
358 i += 2;
359 addFlag = !addFlag;
360
361 Thread.yield();
362 } while (term.compareTo(tolerance) > 0);
363
364 return sum;
365 }
366
367 /**
368 * Compute the square root of x to a given scale, x >= 0.
369 * Use Newton's algorithm.
370 * @param x the value of x
371 * @param scale the desired scale of the result
372 * @return the result value
373 */
374 public static BigDecimal sqrt(BigDecimal x, int scale)
375 {
376 // Check that x >= 0.
377 if (x.signum() < 0) {
378 throw new IllegalArgumentException("x < 0");
379 }
380
381 // n = x*(10^(2*scale))
382 BigInteger n = x.movePointRight(scale << 1).toBigInteger();
383
384 // The first approximation is the upper half of n.
385 int bits = (n.bitLength() + 1) >> 1;
386 BigInteger ix = n.shiftRight(bits);
387 BigInteger ixPrev;
388
389 // Loop until the approximations converge
390 // (two successive approximations are equal after rounding).
391 do {
392 ixPrev = ix;
393
394 // x = (x + n/x)/2
395 ix = ix.add(n.divide(ix)).shiftRight(1);
396
397 Thread.yield();
398 } while (ix.compareTo(ixPrev) != 0);
399
400 return new BigDecimal(ix, scale);
401 }
402 }