BigDecimal.movePointRight () freezes with very large numbers

The following program freezes and I can’t understand why.

import java.math.*; public class BigDec { public static BigDecimal exp(double z) { // Find e^z = e^intPart * e^fracPart. return new BigDecimal(Math.E).pow((int)z, MathContext.DECIMAL128). multiply(new BigDecimal(Math.exp(z-(int)z)), MathContext.DECIMAL128); } public static void main(String[] args) { // This works OK: BigDecimal x = new BigDecimal(3E200); System.out.println("x=" + x); System.out.println("x.movePointRight(1)=" + x.movePointRight(1)); // This does not: x = exp(123456789); System.out.println("x=" + x); System.out.println("x.movePointRight(1)=" + x.movePointRight(1)); //hangs } } 

For real purposes, the first method simply creates a very large BigDecimal. (Details: it finds e in degree z, even if it is too large to be double. I am sure this method is correct, although MathContexts may not be in the best places.)

I know that e ^ 123456789 is extremely large, but I really want to use such numbers. Any answers would be greatly appreciated.

+6
source share
1 answer

In fact, it does not freeze, but the implementation of movePointRight in Oracle VM can be extremely inefficient. It is often much faster to multiply or divide by a power of 10 instead of using the movePointRight or movePointLeft . In your case, using x.multiply(BigDecimal.TEN) will probably work a lot better.

+4
source

Source: https://habr.com/ru/post/908329/


All Articles