1

I'm reading some code that someone else wrote in C#, and I've come across a function similar to the following:

public double calculate(double radianAngle)
{
    double sine = Math.Sin(radianAngle);
    double cosine;
    if(angle > 0.0 && angle < Math.PI / 2.0)
        cosine = Math.Sqrt(1.0 - sine * sine);
    else
        cosine = Math.Cos(radianAngle);

    // ... unrelated code here

    return resultThatUsesSineAndCosine;
}

What this code seems to be referring to is the math identity:

(cos(x))^2 = 1 - (sin(x))^2

But why would you need to add an if statement for this? And why do it in the first place if it's just going to be equal to Math.Cos(radianAngle)? Is there a reason such as better accuracy? Or is this micro-optimization? Or could it be that this code was micro-optimized in another language (C++) then ported to C# with the micro-optimization intact? And even if was micro-optimization, why would it only work for angles between 0 and pi/2?

9a3eedi
  • 696
  • 2
  • 7
  • 18
  • I would say that you are right and it is just a microoptimization from somewhere else. and in terms of [0..90] - both sin and cos > 0 on that range – JleruOHeP Nov 21 '14 at 01:26
  • 1
    Interesting related info http://stackoverflow.com/questions/2683588/what-is-the-fastest-way-to-compute-sin-and-cos-together – mclaassen Nov 21 '14 at 02:41

0 Answers0