我在 C# 中的 Mandelbrot 草图程序无法正常工作

My Mandelbrot sketching program in c# isn't working

我必须制作一个 c# 程序来创建一个表单,并且其中一个控件必须是一个控件,该控件可以绘制 Mandelbrot 集的草图,您可以在其中放大并告诉您要居中的点。在我看来,我做的是对的,但是当我想启动程序时,我没有得到所需的标准 Mandelbrot 集图像。对于 Mandelbrot 草图控件,我有下一个 Mandelbrot class:

class Mandelbrotsketchscreen : UserControl
{
    //a method that draws every point with a certain paint
    //a method that chooses the right colour
    //a method that translates the pixel coordinates of the control to the actual coordinates

    //gives the number how many times the function has to be used
    private static int Mandelnumber(PointF p, PointF middle, double scale, int max, Size size) 
    {
        PointF realpoint = new PointF();
        realpoint.X = (float)(middle.X + (p.X - size.Width / 2) * scale);
        realpoint.Y = (float)(middle.Y + (p.Y - size.Height / 2) * scale);
        PointF help = new PointF(0, 0);
        int i;
        for (i = 1; i <= max; i++)
        {
            help.X = help.X * help.X - help.Y * help.Y + realpoint.X;
            help.Y = 2 * help.X * help.Y + realpoint.Y;

            if (Math.Sqrt(help.X * help.X + help.Y * help.Y) > 2)
                break;
        }
        return i;
    }
}

有人可以告诉我是我计算错误还是我的循环有误吗?

我现在得到的结果是:

help.Xhelp.Y的新值需要根据help.Xhelp.Y的先前值计算得到。

你的代码首先根据之前的help.Xhelp.Y[=39计算出新的help.X值=] 值。到目前为止,一切都很好。但是,您的代码使用新的 help.X 值而不是 previous [ 来计算 help.Y =47=]值。

因此,solution/fix您的问题可以很简单:

    for (i = 1; i <= max; i++)
    {
        var newX = help.X * help.X - help.Y * help.Y + realpoint.X;
        var newY = 2 * help.X * help.Y + realpoint.Y;

        help.X = newX;
        help.Y = newY;

        if (Math.Sqrt(help.X * help.X + help.Y * help.Y) > 2)
            break;
    }

(旁注:我的示例中的 newY 变量并不是绝对必要的。我选择使用它来清楚地说明 [=47 的先前值和新值之间的区别=] 和 help.Y.)


Eric Lippert 在评论中提到了一个不同的(和更短的)解决方案:只需创建一个新的 help 点而不是 mutating/modifying 现有的 help 点:

    for (i = 1; i <= max; i++)
    {
        help = new PointF(
            help.X * help.X - help.Y * help.Y + realpoint.X,
            2 * help.X * help.Y + realpoint.Y
        );

        if (help.X * help.X + help.Y * help.Y > 4)
            break;
    }

这个较短的解决方案还通过与 2 (= 4) 的平方进行比较,消除了相当缓慢的平方根计算。