Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal symbols/parenthesis

I'm trying force BigDecimal to use symbols (Ex. Instead of Decimal.multiply, do Decimal *), because of the mass parenthesis being involved in this problem.

Can you guys tell me if there's a way to use symbols on BigDecimal without converting it to Double or something? Or can you convert t into a format like term?

double t = ((1.00 / f1) * ((((4.00 / (ak1 + 1.00)) - (2.00 / (ak1 + 4.00))) - (1.00 / (ak1 + 5.00))) - (1 / (ak1 + 6.00))));

To a format like

term = ((one.divide(f,mc)).multiply(((((four.divide((ak.add(one)),mc)).subtract((two.divide((ak.add(four)),mc)))).subtract((one.divide((ak.add(five)),mc)))).subtract((one.divide((ak.add(six)),mc))))));

I've tried recording it lots of times, and spent almost 6 hours trying to figure out where I'm getting wrong with the BigDecimal.

like image 809
Muhatashim Avatar asked Dec 27 '22 10:12

Muhatashim


2 Answers

No. Unfortunately Java does not support operator overloading. You have no choice but to use those methods on BigDecimal.

like image 199
missingfaktor Avatar answered Jan 08 '23 10:01

missingfaktor


Nope. Since there is no operator overloading in Java.

To make things simpler for yourself write the equation out in parts and identity the bits that are complicated or repeated several times. Break up your computation into these parts and even write helper methods to help you get the sum computed. If you write the whole computation in parts then each part is easier to test.

eg.

import static java.math.BigDecimal.ONE;

public class Sum {

    private static final TWO = new BigDecimal("2");
    private static final FOUR = new BigDecimal("4");
    private static final FIVE = new BigDecimal("5");
    private static final SIX = new BigDecimal("6");

    private BigDecimal f;
    private BigDecimal ak;

    private MathContext mc;

    public Sum(BigDecimal f, BigDecimal ak, MathContext mc) {
        this.f = f;
        this.ak = ak;
        this.mc = mc;
    }

    public BigDecimal calculate() {

        return inverse(f).multiply(
            firstSubtractRest(
                xOverYPlusZ(FOUR, ak, ONE),
                xOverYPlusZ(TWO, ak, FOUR),
                xOverYPlusZ(ONE, ak, FIVE),
                xOverYPlusZ(ONE, ak, SIX),

            ));

    }

    private BigDecimal inverse(BigDecimal x) {
        return ONE.divide(x, mc);
    }

    /* returns x / (y + z) */
    private BigDecimal xOverYPlusZ(BigDecimal x, BigDecimal y, BigDecimal z) {
        BigDecimal divisor = y.add(z);
        return x.divide(divisor, mc);
    }

    private BigDecimal firstSubtractRest(BigDecimal... values) {
        BigDecimal value = values[0];
        for (int i = 1; i < values.length; i++) {
            value = value.subtract(values[i]);
        }
        return value;
    }

}
like image 34
Dunes Avatar answered Jan 08 '23 10:01

Dunes