Reputation:
I'm using the following code to convert radians to degrees and do some arithmetic on the same.
private double getDegrees(double rad)
{
double deg = rad * Mathf.Rad2Deg;
double degree = (-135 - deg) % 360;
return degree;
}
The value calculates is inaccurate. I'm using the same code in Python and the result is quite accurate as follows,
def getDegree(rad):
return (-135 - math.degrees(rad)) % 360
How do I get the accurate degrees with c#?
Input: -2.54 Output: 10.750966993188058
Input 2.57 Output 77.6960764459401
Input -0.62 Output 260.9199271359733
Input 0.52 Output 195.1409838350769
Note: The output is after (-135 - deg) % 360;
The output from c# is as follows,
Input -2.54 Output 11.0295281217168
Input 2.56 Output -282.127098553015
Input -0.63 Output -98.8646242270579
Input 0.51 Output -164.592296943409
Upvotes: 5
Views: 338
Reputation: 38757
Since the %
operator will return negative values in C# when the input is negative, you'll have to convert them back to positive by adding 360:
private double getDegrees(double rad)
{
double deg = rad * Mathf.Rad2Deg;
double degree = (-135 - deg) % 360;
return degree < 0 ? degree + 360 : degree;
}
Upvotes: 4