title: Get Random XYZ on surface of Sphere from Sphere Loc and Radius
body: <p>I am trying to get random X Y Z coordinates on the surface of a sphere, based on the spheres center in X Y Z, and it's radius in PHP. Currently, my system is just purely random, hoping for a position on the planets center. I'm inept in math so please bear with me (dyscalculia and dyslexia). </p>
  
  <p>Right now I have just random chaos as follows (note randint is a custom function that checks for <code>rand_int</code>, <code>mt_rand</code> and <code>rand</code> and uses the newest. </p>
  
  <pre><code>            $nx = randint( abs( $poo['x'] - $max_distance_x ), abs( $poo['x'] + $max_distance_x ) );
              $ny = randint( abs( $poo['y'] - $max_distance_y ), abs( $poo['y'] + $max_distance_y ) );
              $nz = randint( abs( $poo['z'] - $max_distance_z ), abs( $poo['z'] + $max_distance_z ) );
  </code></pre>
  
  <p>but I have the planet radius <code>$pradius</code>, and planet XYZ center array $poo <code>poo(x, y, z)</code>, and I think I can get random surface X Y Z, just not sure. I've looked at other languages but am having trouble understanding anything to port. </p>
  
  <p><strong><em>Update</em></strong></p>
  
  <p>Based on the two methods provided in an answer I have come up with the following two functions. However both to not function correctly.</p>
  
  <p>The following function only produces craters (points) on the top of the planetoid (north pole), even though it should be calculating from planetoid center at it's radius. </p>
  
  <pre><code>function basic_spheroid_point( $cx, $cy, $cz, $r ) {
  
      $x = randint(-$r, $r);
      $y = randint(-$r, $r);
      $z = randint(-$r, $r);
  
      $dx = $x - $cx;
      $dy = $y - $cy;
      $dz = $z - $cz;
  
      $dd = sqrt( ( $dx * $dx ) + ( $dy * $dy ) + ( $dz * $dz ) );
  
      if ( $dd &gt; $r )
  
          return basic_spheroid_point( $cx, $cy, $cz, $r );
  
      $dx = $r * $dx / $dd;
      $dy = $r * $dy / $dd;
      $dz = $r * $dz / $dd;
  
      return array( $cx + $dx, $cy + $dy, $cz + $dz );
  
  }
  </code></pre>
  
  <p>This function bunches craters at the North Pole of the planet, though there is also global coverage craters so it is working partially. </p>
  
  <pre><code>function uniform_spheroid_point($cx, $cy, $cz, $r) {
  
      $ap = randint( 0, 359 );
      $aq = randint( 0, 359 );
  
      $dx = $r* cos( $ap ) * cos( $aq );
      $dy = $r * sin( $aq );
      $dz = $r * sin( $ap ) * cos( $aq );
  
      return array( $cx + $dx, $cy + $dy, $cz + $dz );
  
   } 
  </code></pre>