生成 C++ 中圆中的随机点
假设我们知道圆心半径和 x-y 位置,我们需要编写一个名为 randPoint() 的函数,该函数可在圆中生成均匀的随机点。因此,有一些重要事项需要牢记 −
- 输入和输出值是浮点数。
- 圆心的半径和 x-y 位置传递给类构造函数。
- 圆周上的点被认为在圆中。
- randPoint() 以该顺序返回随机点的 x 位置和 y 位置。
因此,如果输入类似于 [10, 5,-7.5],则它可能会生成一些随机点,例如 [11.15792,-8.54781],[2.49851,-16.27854],[11.16325,-12.45479]。
要解决此问题,我们将执行以下步骤 −
- 定义一个名为 uniform() 的方法。其工作方式如下 −
- return random_number/MAX RANDOM
- 通过初始化器初始化 rad 和中心坐标
- randPoint 将按如下方式工作 −
- theta = 2*Pi*uniform()
- r := uniform() 的平方根
- 返回像 (center_x + r*radius*cos(theta), center_y + r*radius*sin(theta)) 这样的对
让我们看看以下实现以加深理解 −
示例
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
const double PI = 3.14159265358979732384626433832795;
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 * 3.14159265358979323846264 * uniform();
double r = sqrt(uniform());
return vector<double>{
m_x_center + r * m_radius * cos(theta),
m_y_center + r * m_radius * sin(theta)
};
}
};
main(){
Solution ob(10, 5, 7);
print_vector(ob.randPoint());
print_vector(ob.randPoint());
print_vector(ob.randPoint());
}输入
Pass 10, 5, 7 into constructor Call randPoint() three times
输出
[1.5441, 9.14912, ] [-1.00029, 13.9072, ] [10.2384, 6.49618, ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP