5

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
  • 5
    Please define `inaccurate` for this case. Floating point math is almost never *100%* accurate. – Peter B Mar 09 '20 at 08:26
  • 1
    From the fact you've got a negative number in your example and that you're comparing C# and Python, there's a chance you're getting negative numbers out. Try adding 360 to your result if it's negavtive. – Rawling Mar 09 '20 at 08:29
  • 1
    I have included the input and the output –  Mar 09 '20 at 08:30
  • 3
    Yes - input, actual output and *expected* output is important. At the moment we don't know whether you're getting *radically* different results, or whether this is a precision issue. – Jon Skeet Mar 09 '20 at 08:33
  • 2
    % behaves differently across languages for negative numbers – bolov Mar 09 '20 at 08:34
  • i have included the result in c# @John –  Mar 09 '20 at 08:36
  • @bolov wow! that seems interesting –  Mar 09 '20 at 08:36
  • 2
    What has been said before the `%` operator is different between python and c#, see https://stackoverflow.com/q/18106156/10608418 for a related question and a link to explanation. –  Mar 09 '20 at 08:40
  • @knoop @bolov that was the issue..... thank you so much to both and everyone who tried to help me out.. I have wasted 1 full day trying to figure out what went wrong. `((degree) % 360) + 360) % 360;` fixed the issue. –  Mar 09 '20 at 08:47
  • 1
    @JonSkeet You mean _radiantly_ different results? :) – silkfire Mar 09 '20 at 09:00
  • 1
    @user1241241 Note that if your radian value is significantly positive (e.g. `8`), the solution mentioned in your comment may still return a negative value. – ProgrammingLlama Mar 09 '20 at 09:03

1 Answers1

4

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;
}

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86