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?