2

我正在练习考试,我正在做一个练习题。我有一个带有两个参数的方法:一个是圆的半径,一个是要放置在该圆内的点数。方法如下:

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对象的 x 坐标和 y 坐标以保持在半径范围内。说半径是100,点数是200,我如何将对象保持在该半径内?

该问题指出:

“为了将点包含在半径为 r 的圆内,选择区间 -r, r 中的随机 y 坐标。然后在区间 -b, b 中随机选择 x 坐标,其中 b = sqrt(r^ 2 - y^2)。”

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

这是我失败的输出:

在此处输入图像描述

4

3 回答 3

5

从中心到点的距离(0,0)必须小于圆的半径,r。距离可以表示为sqrt(x² + y²)y因此,如果您在 之间随机选择坐标[-r, r],您只需要确保您的x坐标尊重前面的方程,因此您的数学。

示范

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

您的算法应如下所示。一旦你选择了 y 坐标,你可以随机选择 x,只要它尊重距离约束。

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();
    }
}
于 2013-10-28T08:24:07.900 回答
1

目前你是在圆上画点,而不是在里面。那是因为您没有正确遵循指南。

b = pow((pow(radius,2)-pow(ycord,2)),0.5); // this should be b
xcord = -b + random()*(b+b);
于 2013-10-28T08:21:37.107 回答
1

查看 random 的文档,您会看到默认情况下它会生成一个介于 0 和 1 之间的数字。

基本上这意味着您正在寻找的表达式是: ycord=-radius+random()*(radius*2);

这会在 -radius 和 radius 之间为您提供 y 轴上的一个点(考虑如果 random() 返回 0 你得到 -radius,它返回 1 你得到 -radius+(2*radius())=radius。

您对 x 坐标的计算是正确的,但它会为您提供圆上的 x 坐标点(我们称之为 b)。我怀疑您想使用新的随机数来选择 b 和 -b 之间的 x 坐标。

于 2013-10-28T08:27:07.007 回答