title: Quickly square a double
body: <p>I am looking for the fastest way to square a double (<code>double d</code>). So far I came up with two approaches:</p>
  
  <pre><code>1. d*d
  2. Math.pow(d, 2)
  </code></pre>
  
  <p>To test the performance I set up three test cases, in each I generate random numbers using the same seed for the three cases and just calculate the squared number in a loop 100 000 000 times.</p>
  
  <p>In the first test case numbers are generated using <code>random.nextDouble()</code>, in the second case using <code>random.nextDouble()*Double.MAX_VALUE</code> and in the third one using  <code>random.nextDouble()*Double.MIN_VALUE</code>.</p>
  
  <p>The results of a couple of runs (approximate results, theres always some variation, run using java 1.8, compiled for java 1.6 on Mac OSX Mavericks)</p>
  
  <pre><code>Approach | Case 1 | Case 2 | Case 3
  ---------•--------•--------•-------
      1    | ~2.16s | ~2.16s | ~2.16s
      2    | ~9s    | ~30s   | ~60s
  </code></pre>
  
  <p>The conclusion seems to be that approach 1 is way faster but also that <code>Math.pow</code> seems to behave kind of weird.</p>
  
  <p>So I have two questions:</p>
  
  <ol>
  <li><p>Why is <code>Math.pow</code> so slow, and why does it cope badly with <code>&gt; 1</code> and even worse with <code>&lt; -1</code> numbers?</p></li>
  <li><p>Is there a way to improve the performance over what I suggested as approach 1? I was thinking about something like:</p>
  
  <pre><code>long l = Double.doubleToRawLongBits(d);
  long sign = (l &amp; (1 &lt;&lt; 63));
  Double.longBitsToDouble((l&lt;&lt;1)&amp;sign);
  </code></pre></li>
  </ol>
  
  <p>But that is a) wrong, and b) about the same speed as approach 1.</p>