用于绘制的画布是一个圆;画布内的随机点 [英] Canvas for drawing is a circle; random dots within canvas

查看:104
本文介绍了用于绘制的画布是一个圆;画布内的随机点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为考试做练习,并且正在做其中一个练习题.我有一个带有两个参数的方法:一个用于圆的半径,一个用于放置在该圆内的点数.方法如下:

I'm practicing for an exam, and I'm doing one of the practice problems. I have a method that takes two arguments: one for the radius of a circle, and one for the number of dots to place within that circle. The method is below:

private void drawDots(int radius, int numDots){
    double ycord;
    double xcord;
    for(int q = 0; q < numDots; q++){
        ycord = -radius + random()*(radius+radius+1);
        xcord = pow((pow(radius,2)-pow(ycord,2)),0.5);
        turt.moveTo(xcord,ycord);
        turt.penDown();
        turt.forward(0);
        turt.penUp();
    }
}

turt是我用来绘制的对象,而penDown()/penUp()分别是在画布上放置和删除对象.

turt is an object I'm using to draw with, and penDown()/penUp() is placing and removing the object from the canvas respectively.

我试图定义turt对象的x坐标和y坐标以保持在半径之内.假设半径为100,点数为200,如何将对象保持在该半径内?

I'm trying to define the x-coordinate and y-coordinate of the turt object to stay within a radius. Say the radius is 100, and the number of dots is 200, how do I keep the object within that radius?

问题指出:

为了将点包含在半径为r的圆中,在-r,r间隔中选择了一个随机y坐标.然后在-b,b间隔中随机选择了x坐标,其中b = sqrt (r ^ 2-y ^ 2)."

"To constain the dots to a circle of radius r, a random y-coord in the interval -r, r is chosen. To x-coord is then randomly chosen in the interval -b, b, where b = sqrt(r^2 - y^2)."

我只是不确定如何理解这个数学.上面的代码是我的最佳尝试,但输出结果很奇怪.

I'm just not sure how to make sense of this math. The code above was my best attempt, but the output is strange.

这是我的输出失败:

推荐答案

从中心(0,0)到点的距离必须小于圆的半径r.距离可以表示为sqrt(x² + y²).因此,如果您在[-r, r]之间随机选择y坐标,则只需确保x坐标遵守先前的等式,即可数学.

The distance from the center (0,0) to a dot must be less than the radius of the circle, r. The distance can be expressed as sqrt(x² + y²). Therefore, if you choose your y coordinate randomly between [-r, r], you just have to make sure that your x coordinate respects the previous equation, hence your math.

示范

sqrt(x² + y²) < r
x² + y² < r²
x² < r² - y²
x < sqrt(r² - y²)
#

您的算法应如下.选择y坐标后,您可以随机选择x,只要它符合距离约束即可.

Your algorithm should be as follows. Once you chose the y coordinate, you can randomly choose x as long as it respects the distance constraint.

private void drawDots(int radius, int numDots){
    double y;
    double x;
    double xMax;

    for (int q = 0; q < numDots; q++){
        // y is chosen randomly
        y = -radius + random() * (radius + radius + 1);

        // x must respect x² + y² < r²
        xMax = pow((pow(radius,2)-pow(ycord,2)), 0.5);
        x = random() * 2 * xMax - xMax;

        turt.moveTo(x, y);
        turt.penDown();
        turt.forward(0);
        turt.penUp();
    }
}

这篇关于用于绘制的画布是一个圆;画布内的随机点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆