3

I am running into something that should be very simple to answer but i can't put my fingers on it. It has been quite sometime since i have done some trigonometry.

double cosValue = -2.7105054312E-20;
// (ACos) returns the angle
var deducedAngleInRadian = System.Math.Acos(cosValue);
var cos = System.Math.Cos(deducedAngleInRadian);

Console.WriteLine(cosValue);
Console.WriteLine(deducedAngleInRadian);
Console.WriteLine(cos);

Output:

-2.7105054312E-20
1.5707963267949
6.12303176911189E-17

How come that cosValue and cos are not the same?

O. Jones
  • 103,626
  • 17
  • 118
  • 172
Sam
  • 875
  • 10
  • 22

1 Answers1

2

Did you notice how much the two values are close of 0, and close to each other ?

The floating point (im)precision and the implementation of each methods may probably perfectly explain that. Those methods are not perfect, for example they are relying on an approximation of Pi (of course, as Pi can't be stored in a computer ;)).

You could probably achieve a better precision (do you really need it) with a scientifical library, dedicated to this and using higher precision types than Double. You could may be find some interesting stuff in Math operations using System.Decimal in C#? or https://stackoverflow.com/questions/1387430/recommended-math-library-for-c-net

Community
  • 1
  • 1
AFract
  • 8,868
  • 6
  • 48
  • 70
  • No i didn't notice that initially. I was rather surprised that the values are not the same. – Sam Feb 05 '15 at 21:12
  • I understand that. You can compute Cos(6.12303176911189E-17), it will probably output a result very close to the related angle. It could be interessant to loop other it, to see if the drift increase continuously after a few iterations :). I hope my answer was helpful ! – AFract Feb 05 '15 at 21:21