在Mandelbrot 集中“缩放”特定区域

63 阅读2分钟

0625(1).png

1、问题背景

在创建一个快速生成 Mandelbrot 集图像的 Python 程序时,程序开发者遇到一个问题:他想要渲染该集合的一个特定区域,但他不知道如何修改代码中的数学部分来实现 “缩放”。

2、解决方案

第一种解决方案

  • 问题根源是代码中的一行:box=((-2,1.25),(0.5,-1.25)),因为这条线定义了要渲染的坐标空间区域。

  • 解决方案:  调整 box 值以修改渲染的 Mandelbrot 集区域。

  • 具体步骤:

    • 确定要缩放的矩形区域的坐标(例如,左上角坐标为 (-0.75, 0.1),右下角坐标为 (-0.5, -0.1))。
    • 修改 box 行为 box = ((-0.75, 0.1), (-0.5, -0.1))

第二种解决方案

  • 要缩放 Mandelbrot 集,需要理解 coords = (uleft[0] + (x/size[0]) * (xwidth),uleft[1] - (y/size[1]) * (ywidth)) 的作用。

  • 这行代码将屏幕坐标转换为复平面坐标。

  • 缩放的原理是:

    • 取屏幕坐标的左上角和右下角坐标。
    • 将这些坐标转换为复平面坐标。
    • 使用这些新的坐标作为 uleft 和 lright
  • 解决方案:

    • 确定要缩放的矩形区域的屏幕坐标(例如,左上角坐标为 (100, 100),右下角坐标为 (200, 200))。

    • 将这些坐标转换为复平面坐标,例如:

      • new_uleft = (uleft[0] + (100/size[0]) * (xwidth), uleft[1] - (100/size[1]) * (ywidth))
      • new_lright = (uleft[0] + (200/size[0]) * (xwidth), uleft[1] - (200/size[1]) * (ywidth))
    • 重新计算 sizexwidthywidth 和其他相关变量。

代码例子

以下提供了一个参考实现:

import complex

def mandelbrot_zoom(uleft, lright, size, n):
    """
    Generate a Mandelbrot set image with a zoomed-in area.

    Args:
    uleft: Complex number representing the upper-left corner of the zoomed-in area.
    lright: Complex number representing the lower-right corner of the zoomed-in area.
    size: Tuple representing the size of the image (width, height).
    n: Maximum number of iterations to check for divergence.

    Returns:
    A list of lists of colors, where each color represents a pixel in the image.
    """

    # Calculate the width and height of the zoomed-in area.
    xwidth = lright.real - uleft.real
    ywidth = uleft.imag - lright.imag

    # Create a list to store the colors of the pixels.
    image = [[0 for _ in range(size[0])] for _ in range(size[1])]

    # Iterate over each pixel in the image.
    for y in range(size[1]):
        for x in range(size[0]):
            # Convert the pixel coordinates to complex coordinates.
            coords = (uleft.real + (x / size[0]) * xwidth,
                     uleft.imag - (y / size[1]) * ywidth)

            # Initialize the complex number z and the number of iterations.
            z = complex(0, 0)
            trials = 0

            # Iterate until z diverges or the maximum number of iterations is reached.
            while abs(z) <= 2.0 and trials < n:
                z = z**2 + coords
                trials += 1

            # Set the color of the pixel based on the number of iterations.
            image[y][x] = trials

    return image

# Example usage:
uleft = complex(-0.75, 0.1)
lright = complex(-0.5, -0.1)
size = (500, 500)
n = 64

image = mandelbrot_zoom(uleft, lright, size, n)

您可以根据自己的需要调整 uleftlrightsize 和 n 的值来生成想要的 Mandelbrot 集缩放图像。