Search code examples
c#functiontrigonometrymath-functions

C# trigonometric functions / math functions


I'm writing a class which should calculate angles (in degrees), after long trying I don't get it to work.

When r = 45 & h = 0 sum should be around 77,14°

but it returns NaN - Why? I know it must be something with the Math.Atan-Method and a not valid value.

My code:

    private int r = 0, h = 0;
    public Schutzwinkelberechnung(int r, int h)
    {
        this.r = r;
        this.h = h;
    }
    public double getSchutzwinkel()
    {
        double sum = 0;

        sum = 180 / Math.PI * Math.Atan((Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(Math.Asin((Math.Sqrt(2 * h * r)) / (2 * r)))) / (h - r + r * (Math.Cos(Math.Asin(Math.Sqrt(2 * h * r) / (2 * r))))));

        return sum;
    }

Does someone see my mistake? I got the formula from an excel sheet.

EDIT: Okay, my problem was that I had a parsing error while creating the object or getting the user input, apparently solved it by accident. Ofc I have to add a simple exception, as Nick Dechiara said. Thank you very much for the fast reply, I appreciate it.

EDIT2: The exception in my excel sheet is:

if(h < 2) {h = 2}

so that's explaining everything and I wasn't paying attention at all. Thanks again for all answers.

int r = 45, h = 2;
sum = 77.14°

Solution

  • A good approach to debugging these kinds of issues is to break the equation into smaller pieces, so it is easier to debug.

    double r = 45;
    double h = 0;
    
    double sqrt2hr = Math.Sqrt(2 * h * r);
    double asinsqrt2hr = Math.Asin((sqrt2hr) / (2 * r));
    
    double a = (Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(asinsqrt2hr));
    double b = (h - r + r * (Math.Cos(asinsqrt2hr)));
    
    double sum = 180 / Math.PI * Math.Atan(a / b);
    

    Now if we put a breakpoint at sum and let the code run, we see that both a and b are equal to zero. This gives us a / b = 0 / 0 = NaN in the final line.

    Now we can ask, why is this happening? Well in the case of b you have h - r + r which is 0 - 45 + 45, evaluates to 0, so b becomes 0. You probably have an error in your math there.

    In the case of a, we have 2 * h * r - h * h, which also evaluates to 0.

    You probably either A) have an error in your equation, or B) need to include a special case for when h = 0, as that is breaking your math here.