title: matlab and c differ with cos function
body: <p>I have a program implemented in matlab and the same program in c, and the results differ.</p>
  
  <p>I am bit puzzled that the cos function does not return the exact same result.</p>
  
  <p>I use the same computer, Intel Core 2 Duo, and 8 bytes double data type in both cases.</p>
  
  <p>Why does the result differ?</p>
  
  <p>Here is the test:</p>
  
  <pre><code>c:
  double a = 2.89308776595231886830;
  double b = cos(a);
  printf("a = %.50f\n", a);
  printf("b = %.50f\n", b);
  printf("sizeof(a): %ld\n", sizeof(a));
  printf("sizeof(b): %ld\n", sizeof(b));
  
  a = 2.89308776595231886830106304842047393321990966796875
  b = -0.96928123535654842068964853751822374761104583740234
  sizeof(a): 8
  sizeof(b): 8
  
  
  
  matlab:
  a = 2.89308776595231886830
  b = cos(a);
  fprintf('a = %.50f\n', a);
  fprintf('b = %.50f\n', b);
  whos('a')
  whos('b')
  
  a = 2.89308776595231886830106304842047393321990966796875
  b = -0.96928123535654830966734607500256970524787902832031
    Name      Size            Bytes  Class     Attributes
    a         1x1                 8  double              
  
    Name      Size            Bytes  Class     Attributes
    b         1x1                 8  double  
  
  
  So, b differ a bit (very slightly, but enough to make my debuging task difficult)
  
  b = -0.96928123535654842068964853751822374761104583740234  c
  b = -0.96928123535654830966734607500256970524787902832031  matlab
  </code></pre>
  
  <hr>
  
  <p>I use the same computer, Intel Core 2 Duo, and 8 bytes double data type.</p>
  
  <p>Why does the result differ?</p>
  
  <p>does matlab do not use the cos function hardware built-in in Intel?</p>
  
  <p>Is there a simple way to use the same cos function in matlab and c (with exact results), even if a bit slower, so that I can safely compare the results of my matlab and c program?</p>
  
  <hr>
  
  <p><strong>Update:</strong></p>
  
  <p>thanks a lot for your answers!</p>
  
  <p>So, as you have pointed out, the cos function for matlab and c differ.
  That's amazing! I thought they were using the cos function built-in in the Intel microprocessor.</p>
  
  <p>The cos version of matlab is equal (at least for this test) to the one of matlab.
  you can try from matlab also: b=java.lang.Math.cos(a)</p>
  
  <p>Then, I did a small MEX function to use the cos c version from within matlab, and it works fine; This allows me to debug the my program (the same one implemented in matlab and c) and see at what point they differ, which was the purpose of this post.</p>
  
  <p>The only thing is that calling the MEX c cos version from matlab is way too slow.</p>
  
  <p>I am now trying to call the Java cos function from c (as it is the same from matlab), see if that goes faster.</p>