/* the ngon (regular polygon) is composed of 2n congruent triangles. center angle is 360/2n. base is opposite the center angle. height is adjacent to center angle. */ import java.awt.*; import javax.swing.*; import java.text.*; public class PolygonsCircle extends JApplet { public void init() { double b_in, h_in, areaT_in, areaNgon_in; double b_circum, h_circum, areaT_circum, areaNgon_circum ; DecimalFormat d3 = new DecimalFormat ("0.000"); System.out.println("INscribed and Circumscribed regular polygons of unit circle"); System.out.println("N IN: b h At An %c"+ " OUT: b h At An %c"); for (int ngon=3; ngon<20; ngon++) { b_in = Math.sin(Math.toRadians(180.0/ngon)); h_in = Math.sqrt(1 - b_in*b_in); areaT_in = 0.5 * b_in * h_in; areaNgon_in = areaT_in * 2 * ngon; b_circum = Math.tan(Math.toRadians(180.0/ngon)); h_circum = 1; areaT_circum = 0.5 * b_circum * h_circum; areaNgon_circum = areaT_circum * 2 * ngon; System.out.println(""+ngon+" "+d3.format(b_in)+" "+d3.format(h_in)+" "+ d3.format(areaT_in)+" "+d3.format(areaNgon_in)+" "+d3.format((areaNgon_in/Math.PI))+ " "+d3.format(b_circum)+" "+d3.format(h_circum)+" "+ d3.format(areaT_circum)+" "+d3.format(areaNgon_circum)+" "+d3.format((areaNgon_circum/Math.PI))); } } public void paint (Graphics g) { int w = getWidth(); int h = getHeight(); int r = w<=h ? w/2 : h/2; //min of width height int x, y, xn, yn; Color [] colors = {Color.WHITE, Color.BLACK, Color.DARK_GRAY,Color.GRAY,Color.LIGHT_GRAY, Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.YELLOW, Color.MAGENTA, Color.ORANGE, Color.PINK}; g.drawOval(0,0,2*r,2*r); for (int ngon=12; ngon>=3; ngon--) { double angle = 360.0/ngon; Polygon poly = new Polygon(); x = r + r; y = r; //Point p = new Point(x,y); poly.addPoint(x,y); for (int points=1; points<=ngon; points++) { xn = (int)(Math.cos(Math.toRadians(angle*points)) * r + r); yn = (int)(Math.sin(Math.toRadians(angle*points)) * r + r); //g.drawLine(x,y, xn,yn); x = xn; y = yn; poly.addPoint(x,y); } g.setColor(colors[ngon-2]); g.fillPolygon(poly); } } }