Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set all BigDecimal operations to a certain precision?

My Java program is centered around high precision calculations, which need to be accurate to at least 120 decimal places.
Consequentially, all non-integer numbers will be represented by BigDecimals in the program.

Obviously I need to specify the accuracy of the rounding for the BigDecimals, to avoid infinite decimal expressions etc.
Currently, I find it a massive nuisance to have to specify the accuracy at every instantiation or mathematical operation of a BigDecimal.

Is there a way to set a 'global accuracy' for all BigDecimal calculations?
(Such as the Context.prec() for the Decimal module in python)

Thanks


Specs:
Java jre7 SE
Windows 7 (32)

like image 477
Anti Earth Avatar asked Apr 08 '12 03:04

Anti Earth


4 Answers

(Almost) Original

Not as simple, but you can create a MathContext and pass it to all your BigDecimal constructors and the methods performing operations.

Revised

Alternatively, you can extend BigDecimal and override any operations you want to use by supplying the right MathContext, and using the rounding version of divide:

public class MyBigDecimal extends BigDecimal {

      private static MathContext context = new MathContext(120, RoundingMode.HALF_UP);

      public MyBigDecimal(String s) {
           super(s, context);
      }
      public MyBigDecimal(BigDecimal bd) {
           this(bd.toString()); // (Calls other constructor)
      }
      ...
      public MyBigDecimal divide( BigDecimal divisor ){
           return new MyBigDecimal( super.divide( divisor, context ) );
      }
      public MyBigDecimal add( BigDecimal augend ){
           return new MyBigDecimal( super.add( augend ) );
      }
      ...
}
like image 127
trutheality Avatar answered Nov 16 '22 13:11

trutheality


Create a BigDecimalFactory class with static factory methods matching all constructors that accept MathContext - except that the MathContext instance is inside the factory and statically initialized at startup time. Here's a fragment:

public class BigDecimalFactory {
    public static BigDecimal newInstance (BigInteger unscaledVal, int scale) {
        return new BigDecimal (unscaledVal, scale, _mathContext);
    }

    // . . . other factory methods for other BigDecimal constructors

    private static final MathContext _mathContext = 
        new MathContext (120, BigDecimal.ROUND_HALF_UP);
}
like image 4
sparc_spread Avatar answered Nov 16 '22 14:11

sparc_spread


Is there a way to set a 'global accuracy' for all BigDecimal calculations?

No.

You'll have to create a wrapper class that has a MathContext as an extra attribute. It will need to:

  • use this mc for each mathematical operation that would otherwise use the default semantics, and

  • create and return another wrapped instance each time the wrapped operation returns a regular instance.

(As a variation, you could implement a 'global' MathContext using a static, but you'll still need to use wrappering to ensure that the mc is used.)

(Extending BigDecimal would work too, and that is arguable neater than a wrapper class.)


You said this in a comment:

I really don't want to write my own Decimal module, I just want to understand why BigDecimal is being so uncooperative.

(Design questions can only be answered definitively by the design team. However ...)

As with all complicated utility classes, the design of BigDecimal is a compromise that is designed to meet the requirements of a wide range of use-cases. It is also a compromise between the competing meta-requirements (wrong word) of "powerfulness" and "simplicity".

What you have is a use-case that is not particularly well supported. But I suspect that if it was well supported (e.g. with a global MathContext controlling everything or a MathContext attached to each BigDecimal) then that would introduce all sorts of other complexities; e.g. dealing with operations where there are two or more competing context objects to consider. Such problems could be dealt with ... but they are liable to lead to "surprises" for the programmer, and that is not a good thing.

The current approach is simple and easy to understand, and if you need something more complicated you can implement it ... by explicitly supplying a MathContext for the operations that require it.

like image 3
Stephen C Avatar answered Nov 16 '22 14:11

Stephen C


You could create a class that extends BigDecimal and sets the precision automatically for you. Then you just use you that class.

public class MyBigDecimal extends BigDecimal {
      public MyBigDecimal(double d) {
           super(d);
           this.setScale(120, BigDecimal.ROUND_HALF_UP);
      }
      ...
}
like image 1
twain249 Avatar answered Nov 16 '22 14:11

twain249