Guest User

Untitled

a guest
Aug 5th, 2018
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. // C code for https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/
  2. // see HN discussion here https://news.ycombinator.com/item?id=17688599
  3.  
  4. // ============================== getpoint1.c ==============================
  5. #include <stdio.h>
  6. #include <math.h>
  7. #include <stdlib.h>
  8.  
  9. void getPoint(double v[]) {
  10.   double d;
  11.   do {
  12.     v[0] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
  13.     v[1] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
  14.     v[2] = (rand()/(double)RAND_MAX)*2.0 - 1.0;
  15.     d = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
  16.   } while (d > 1.0);
  17. }
  18.  
  19. int main(int argc, char *argv[]) {
  20.  
  21.   double v[3];
  22.   for (int i=0; i<1e7; i++) {
  23.     getPoint(v);
  24.   }
  25.   return 0;
  26. }
  27.  
  28. // ============================== getpoint5.c ==============================
  29. #include <stdio.h>
  30. #include <math.h>
  31. #include <stdlib.h>
  32.  
  33. void getPoint(double vec[]) {
  34.   double u = (rand()/(double)RAND_MAX);
  35.   double v = (rand()/(double)RAND_MAX);
  36.   double theta = u * 2.0 * M_PI;
  37.   double phi = acos(2.0 * v - 1.0);
  38.   double r = cbrt(rand()/(double)RAND_MAX);
  39.   double sinTheta = sin(theta);
  40.   double cosTheta = cos(theta);
  41.   double sinPhi = sin(phi);
  42.   double cosPhi = cos(phi);
  43.   vec[0] = r * sinPhi * cosTheta;
  44.   vec[1] = r * sinPhi * sinTheta;
  45.   vec[2] = r * cosPhi;
  46. }
  47.  
  48. int main(int argc, char *argv[]) {
  49.  
  50.   double vec[3];
  51.   for (int i=0; i<1e7; i++) {
  52.     getPoint(vec);
  53.   }
  54.   return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment