Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Generate Random Point in a Circle สุ่มจุดในวงกลมใน C++

กำหนดรัศมีและตำแหน่งศูนย์กลางวงกลม เขียน randPoint() สุ่มจุดในวงกลมแบบสม่ำเสมอ (uniform)

จุดบนเส้นรอบวงถือว่าอยู่ในวงกลม

วิธีแก้ปัญหา (Polar Coordinates + sqrt for Uniform Distribution)

ใช้พิกัดขั้ว: r = √(uniform()), θ = 2π × uniform()

จุด = (center_x + r×radius×cosθ, center_y + r×radius×sinθ)

ต้องใช้ √uniform() เพื่อกระจายจุดสม่ำเสมอตามพื้นที่ (ไม่ให้หนาแน่นกลาง)

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void print_vector(vector<double> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++) cout << v[i] << ", ";
    cout << "]" << endl;
}

class Solution {
public:
    const double PI = 3.14159265358979323846;
    double m_radius, m_x_center, m_y_center;
    
    double uniform() { return (double)rand() / RAND_MAX; }
    
    Solution(double radius, double x_center, double y_center) {
        srand(time(NULL));
        m_radius = radius; m_x_center = x_center; m_y_center = y_center;
    }
    
    vector<double> randPoint() {
        double theta = 2 * PI * uniform();
        double r = sqrt(uniform());
        return {
            m_x_center + r * m_radius * cos(theta),
            m_y_center + r * m_radius * sin(theta)
        };
    }
};

int main() {
    Solution ob(10, 5, 7);
    for (int i = 0; i < 3; i++) print_vector(ob.randPoint());
    return 0;
}

Input

Pass 10, 5, 7 into constructor, call randPoint() three times

Output

[1.5441, 9.14912, ] [-1.00029, 13.9072, ] [10.2384, 6.49618, ]