title: Arithmetic on large numbers
body: <p>I've been thinking about ways to program for exteme distances, in the game Hellion for example, orbits could be near to scale in the ranges of millions of kilometers. However there was a common glitch where movement would be very choppy the further you were from the object you were orbiting. I might be wrong in my speculation to why that was, but my best guess was that it was down to loss of precision at that distance.</p>
  
  <p>As a little exercise I've been thinking about ways to solve that problem and what I currently have is a a pretty basic unit staged distance system.</p>
  
  <p>
  
  <pre><code>class Distance
  {
      public const MAX_AU = 63018.867924528;
      public const MAX_MM = 149598000000000;
  
      private $ly = 0;
      private $au = 0;
      private $mm = 0;
  
      public function add(Distance $add): Distance
      {
          $distance = new Distance();
          $distance-&gt;mm = $this-&gt;mm + $add-&gt;mm;
  
          if ($distance-&gt;mm &gt; self::MAX_MM) {
              $distance-&gt;mm-= self::self::MAX_MM;
              $distance-&gt;au++;
          }
  
          $distance-&gt;au+= $this-&gt;au + $add-&gt;au;
  
          if ($distance-&gt;au &gt; self::MAX_AU) {
              $distance-&gt;au-= self::self::MAX_AU;
              $distance-&gt;ly++;
          }
  
          $distance-&gt;ly+= $this-&gt;ly + $add-&gt;ly;
  
          return $distance;
      }
  }
  </code></pre>
  
  <p>I put in the addition method, which is written as though by hand. I didn't want to use arbitary precision because it would have been too extreme for calculating the smaller distances a player would normally interact with.</p>
  
  <p>My question is; is this how something like this is normally done? and if not, could someone please explain what is wrong with this (inefficient for example), and how it could be done better?</p>
  
  <p>Thanks</p>
  
  <hr>
  
  <p>PS. I am aware that in the context of a game, this is normally handled with sub-grids, but to simulate how objects in orbit would drift apart, thats what this is for.</p>