2016-12-10 26 views
2

我昨晚在Javascript中做了這個簡單的Mandelbrot Set生成器,但它輸出了一個非常奇怪的結構。我認爲它看起來與mandelbrot集合相似,但奇怪地變形了。我不知道爲什麼它會這樣扭曲,我一直在努力尋找整天。有誰知道是什麼原因或如何解決這個問題?失敗的JS Mandelbrot Set發生器輸出奇數結構

c = document.getElementById("canvas"); 
ctx = c.getContext("2d"); 
c.width = 4000; 
c.height = 4000; 

declareVariables(); 
calculateShape(); 
drawShape(); 

function declareVariables() { 
    Re = -2; 
    Im = -2; 
    input = [Re,Im]; 
    precision = prompt("input precision (higher is better)"); 
    precision = 1/(precision - precision%4); 
    segmentAmt = 4/precision; 
    segmentSize = c.width/segmentAmt; 
    iterate = prompt("input test amount (higher is better)"); 
    set = []; 
    for (i=0; i<segmentAmt; i++) { 
     set[i] = []; 
    } 
    numberGrid = []; 
    for (i=0; i<segmentAmt; i++) { 
     numberGrid[i] = []; 
     for (j=0; j<segmentAmt; j++) { 

     } 
    } 
} 

function calculateShape() { 
    for (i=0; i<segmentAmt; i++) { 
     input[1] = -2; 
     input[0] += precision; 
     for (j=0; j<segmentAmt; j++) { 
      input[1] += precision; 
      set[i][j] = 0; 
      z = [0,0]; 
      for (k=1; k<=iterate; k++) { 
       store = z; 
       z[0] = store[0]**2 - store[1]**2 + input[0]; 
       z[1] = 2 * store[0] * store[1] + input[1]; 
       if (z[0]**2 + z[1]**2 > 4) { 
        set[i][j] = k; 
        k = iterate+1; 
       } 
      } 
     } 
    } 
} 

function drawShape() { 
    ctx.fillStyle = "white"; 
    ctx.fillRect(0,0,c.width,c.height); 
    for (i=0; i<segmentAmt; i++) { 
     for (j=0; j<segmentAmt; j++) { 
      if (set[i][j] == 0) { 
       ctx.fillStyle = "black"; 
      } else if (set[i][j] >= 1) { 
       ctx.fillStyle = 'hsl(' + (25*(set[i][j]-1))**0.75 + ', 100%, 50%)'; 
      } 
      convertCoords(i,j); 
      ctx.fillRect(xCoord,yCoord,segmentSize,segmentSize); 
     } 
    } 
} 

function convertCoords(var1,var2) { 
    xCoord = var1 * segmentSize; 
    yCoord = var2 * segmentSize; 
} 

輸出圖像:

output image

回答

2

的錯誤似乎是在這條線在calculateShape()

   store = z; 

看來你想store作爲複製z,但這只是結束於storez指的是相同的數組。下一行計算z[0],但是因爲storez指的是相同的數組,因此store[0]具有新值z[0]而不是前一個。因此,在此之後的行中計算z[1]是不正確的。

與任一

   store = [z[0], z[1]]; 

   store = z.slice(); 

這兩種線確保store指不同陣列z替換上面的行,所以當重新計算z[0]store[0]不受影響。