Search code examples
pythonpygamefractalscomplex-numbers

How to write a function to map points on a canvas to points on the real plane


I'm writing a simple Mandelbrot visualiser in Python onto a pygame Screen. For each pixel on the 600 by 600 Screen, I am plotting whether or not this pixel, (x, y) as a complex number, is in the Mandelbrot set or not.

The problem being that I start at (0, 0) and iterate through to (600, 600), most of which is outside the set anyways. So I chuck in a scaling factor to zoom in, but I'm still only plotting the upper right quadrant. I would like some way of making it so my plot was always centered around 0+0i.

What I would like to do is find some kind of way to map the 600px^2 canvas to the real plane from [-2, 2] on the x-axis to [2, -2] on the y-axis. This would mean for instance, that the complex number 0+0i would map to (300, 300) on the screen. This way, my plot would always be centered.


Solution

  • You want a window for your data. You know it is 600 pixels wide and 600 pixels tall. The pixel coordinates are (0, 0) - (600, 600). You can do this:

    Point coordFromPixelLocation (pixelX, pixelY, pixelWidth, pixelHeight, minCoordX, maxCoordX, minCoordY, maxCoordY)
    {
        xPercent = pixelX / pixelWidth;
        yPercent = pixelY / pixelHeight;
    
        newX = minCoordX + (maxCoordX - minCoordX) * xPercent;
        newY = minCoordY + (maxCoordY - minCoordY) * yPercent;
    
        return Point (newX, newY);
    }
    

    pixelX and pixelY are the pixel coordinates that you want to convert to the smaller range. pixelWidth and height are the width and height of your window. min/maxCoordX/Y are the (-2,-2) to (2,2) values.