Search code examples
javapi

Calculate the area of a regular polygon issue


I am trying to write a bit of code to calculate the area of a regular polygon with this formula (sides*length^2)/4*tan(Pi/sides) my code looks like

double area = (nSides * Math.pow(sLength, 2)) /
            4 * Math.tan ((Math.PI) / nSides);

I expected that with nSides == 5 and sLength == 6.5, I should get 72.69017017488385 but it outputs 38.370527260283126 instead.


Solution

  • It's called Order of Operations. The Java documentation says it unclearly here:

    The operators in the following table are listed according to precedence order

    The problem is that division and multiplication have equal precedence.

    Operators on the same line have equal precedence. ... All binary operators except for the assignment operators are evaluated from left to right;

    So given they have equal precedence, your division by 4 will be evaluated before the multiplication by Math.tan. You need to explicitly specify the order by inserting an extra set of brackets:

    double area = (nSides * Math.pow(sLength, 2)) /
                  (4 * Math.tan ((Math.PI) / nSides));