Problem with Big Decimal - Calculation process slows down

Hey guys!
i’m very new to Big Decimal
i attempting to calculate mandelbrot set with high precision for ultra zoom capability, so i’m using Big Decimal to perform calculation.
while calculating, the loop slows down. i suspected the problem is in BigDecimal method. looks like it performs a long decimal calculation, the decimal become bigger and bigger so it slowing down. but how is this happened? i have tried some ways like flooring it, but it couldn’t solve the problem

here the simplified codes:

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
MathContext mc = new MathContext(2, RoundingMode.FLOOR);

int maxIter = 100;

void setup() {
  BigDecimal x0 = new BigDecimal("2");
  BigDecimal y0 = new BigDecimal("1");
  BigDecimal x = new BigDecimal("0");
  BigDecimal y = new BigDecimal("0");

  int iteration = 0;   

  // the loop slowing down
  while (iteration < maxIter) {
    BigDecimal xTemp = x.multiply(x).subtract(y.multiply(y)).add(x0);  // = xTemp = x*x - y*y + x0 : am i doing it right?
    y = x.multiply(y).multiply(new BigDecimal("2")).add(y0); // = y =  x*y*2 + y0;
    x = xTemp;    
    //println(xTemp); // the decimal become bigger and bigger, it slows the process
    // the loop slowing down at ~22 loop
    println(iteration);
    iteration++;
  }  
  println("DONE!"); // this line should be executed
}

I have no clue how is this happened. Any help would be appreciated!

Just instantiating MathContext will not apply it to any of the operations. It’s quite inconvenient, but you have to pass it every time again and again: e.g.: new BigDecimal("2", mc), x.multiply(x, mc), etc. You can also use setScale method on already instantiated BigDecimal instance.

Overall scale and precision for BigDecimals might be confusing:

http://www.piotrnowicki.com/2011/02/precision-and-scale-in-bigdecimal-and-mathcontext/

Thanks @morisil, but i have tried setScale and mc before, that MathContext is from the complete code. i passed the mc to every calculation, and tried setScale but it remains the same. it is kinda weird, the xTemp pops out a long decimals.
i tried something like this:

BigDecimal xTemp = x.multiply(x, mc).subtract(y.multiply(y, mc), mc).add(x0, mc).setScale(2, RoundingMode.HALF_DOWN);
y = x.multiply(y, mc).multiply(new BigDecimal("2", mc), mc).add(y0, mc).setScale(2, RoundingMode.HALF_DOWN)

am i doing it right?

oh my gosh! i spot the mistake! silly me :sweat_smile:

i forgot some spot on that complex plane can goes toward infinity. i have to test if it getting bigger and bigger.