Reputation: 2134
I have been training with the following programming exercise: Circles in Polygons. The statement is:
You are the owner of a box making company.
Your company can produce any equal sided polygon box, but plenty of your customers want to transport circular objects in these boxes. Circles are a very common shape in the consumer industry. Tin cans, glasses, tyres and CD's are a few examples of these.
As a result you decide to add this information on your boxes: The largest (diameter) circular object that can fit into a given box.
I have found the following formula:
Taken from: https://www.mathopenref.com/polygonincircle.html
So to calculate the diameter of the largest incircle we have:
sideLength / tan(180/numberOfSides)
I have written the following code:
public class Polygon {
int sides;
int sideLength;
public Polygon(int sides, int sideLength) {
this.sides = sides;
this.sideLength = sideLength;
}
public double circleDiameter /*🔴*/(){
double div = Math.toRadians(180/sides);
System.out.println("div: "+div);
double den = Math.tan(div);
System.out.println("den: "+den);
double diameter = sideLength / den;
System.out.println("diameter: "+diameter);
return diameter;
}
}
However I wonder why it does fail one test and passes two of them. Here are the test, extracted from the exercise:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class PolygonTest {
@Test
public void test1(){
//Square with sides of 5 units
Polygon poly=new Polygon(4, 5);
assertEquals("5.000", String.format("%.3f", poly.circleDiameter()));
}
@Test
public void test2() {
//Octagon with sides of 9 units
Polygon poly=new Polygon(8, 9);
assertEquals("21.728", String.format("%.3f", poly.circleDiameter()));
}
@Test
public void test3() {
//Triangle with sides of 4 units
Polygon poly=new Polygon(3, 4);
assertEquals("2.309", String.format("%.3f", poly.circleDiameter()));
}
}
And our code fails the Octagon test. The trace is:
div: 0.3839724354387525
den: 0.4040262258351568
diameter: 22.275781680746665
expected:<2[1.728]> but was:<2[2.276]>
Why does the code give this result? I have thought that there could be a rounding error. However it is so big that I think it is the formula the one which is wrong.
I have also read:
Upvotes: 1
Views: 1606
Reputation: 362197
double div = Math.toRadians(180/sides);
When sides
is 8 the result should be 22.5, but because both 180 and sides
are integers the calculation is done using integer math, yielding 22.
Change one or both operands to doubles to ensure there's no inadvertent rounding:
double div = Math.toRadians(180.0/sides);
Upvotes: 3