In: Computer Science
All Tasks are commented in the code:
public class MandelbrotUtil {
private MandelbrotUtil() {
}
/**
* Return the number of iterations needed to determine if z(n + 1) = z(n) * z(n) + c
* remains bounded where z(0) = 0 + 0i. z(n + 1) is bounded if its magnitude
* is less than or equal to 2. Returns 1 if the magnitude of c
* is greater than 2. Returns max if the magnitude
* of z(n + 1) is less than or equal to 2 after max iterations.
*
* <p>
* If z(n + 1) remains bounded after max iterations then c is assumed to
* be in the Mandelbrot set.
*
* @param c a complex number
* @param max the maximum number of iterations to attempt
* @return the number of iterations needed to determine if z(n + 1) = z(n) * z(n) + c
* remains bounded where z(0) = 0.0 + 0.0i.
* @pre. max is greater than 0
*/
public static int mandelbrotIterations(Complex c, int max) {
Complex z = new Complex(0.0, 0.0);
// You need a loop here. Inside the loop, set z to z * z + c
// (i.e. perform one iteration of the equation) and
// check if the magnitude of z is greater than 2; if
// the magnitude is greater than 2 then return the
// number of times you computed z * z + c.
// If you compute z * z + c max times and the magnitude
// of z is still less than or equal to 2 you should
// return max.
return max;
}
}
public class MandelbrotUtil {
private MandelbrotUtil() {
}
public static int mandelbrotIterations(Complex c, int max) {
Complex z = new Complex(0.0,0.0);
for (int t = 0; t < max; t++) {
if (abs(z) > 2.0) return t;
z = times(z,z);
z = plus(z,c);
}
return max;
}
// HELPER FUNCTIONS
public static double abs(Complex c){ //Function
to calculate the absolute value of Complex number
double ab;
ab = Math.hypot(c.real, c.imag);
return ab;
}
// return a new Complex object whose value is (this * b)
public static Complex times(Complex a,Complex b) {
//Multiplying two Complex numbers
double real = a.real * b.real - a.imag * b.imag;
double imag = a.real * b.imag + a.imag * b.real;
return new Complex(real, imag);
}
public static Complex plus(Complex a, Complex b){
//Adding two Complex numbers
double real = a.real+b.real;
double imag = b.imag+a.imag;
return new Complex(real,imag);
}
}
Complex number class:
public class Complex {
double real,imag;
public Complex(double a, double b){
real=a;
imag=b;
}
}