Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // C code for https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/
- // see HN discussion here https://news.ycombinator.com/item?id=17688599
- // ============================== getpoint1.c ==============================
- #include <stdio.h>
- #include <math.h>
- #include <stdlib.h>
- void getPoint(double v[]) {
- double d;
- do {
- v[0] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
- v[1] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
- v[2] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
- d = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
- } while (d > 1.0);
- }
- int main(int argc, char *argv[]) {
- double v[3];
- for (int i=0; i<1e7; i++) {
- getPoint(v);
- }
- return 0;
- }
- // ============================== getpoint5.c ==============================
- #include <stdio.h>
- #include <math.h>
- #include <stdlib.h>
- void getPoint(double vec[]) {
- double u = (rand()/(double)RAND_MAX);
- double v = (rand()/(double)RAND_MAX);
- double theta = u * 2.0 * M_PI;
- double phi = acos(2.0 * v - 1.0);
- double r = cbrt(rand()/(double)RAND_MAX);
- double sinTheta = sin(theta);
- double cosTheta = cos(theta);
- double sinPhi = sin(phi);
- double cosPhi = cos(phi);
- vec[0] = r * sinPhi * cosTheta;
- vec[1] = r * sinPhi * sinTheta;
- vec[2] = r * cosPhi;
- }
- int main(int argc, char *argv[]) {
- double vec[3];
- for (int i=0; i<1e7; i++) {
- getPoint(vec);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment