# Trigonometry and Pi in Java

• 04-12-2012, 12:29 AM
boj
Trigonometry and Pi in Java
Yesterday in math class, my math teacher showed the class how the ancient Greeks calculated Pi. They took a polygon and measured the radius and compared it to the area. Then they added another side to the polygon, and recalculated. The more sides the polygon had, the closer it was to Pi. The formula is Area = N * 1/2 sin (360/n) where N is the number of sides. So, I looked up how to do trig in Java and found that it was Math.sin, Math.cos, etc. But then I read closer and found that Java calculated in radians. I tried converting 2 and 360 to radians to plug into my equation, but when I ran the code it came up with somewhere along the lines of 10,313. Here is my code:
Code:

public class Pi {
public static void main(String [] args) {
System.out.print("How many sides should the program calculate for? Enter your answer here:");
double Sides = IO.getlnDouble();
System.out.println("");
double calculatedPi = 0;
while(true) {
double sinofanglec = Math.sin(360/Sides);
calculatedPi = Sides * sinofanglec / 2;
calculatedPi = Math.toDegrees(calculatedPi);
System.out.println(calculatedPi);
Sides = Math.toDegrees(Sides);
Sides++;
}
}
}

It is worth mentioning that for I/o, I use some code that someone else wrote, called TextIO, because I am fairly new to Java. I just renamed it to IO, so that's what I reference in my code.
• 04-12-2012, 01:08 AM
doWhile
Re: Trigonometry and Pi in Java
It always helps to write out your algorithm in a stepwise manner, then translate those steps to code: your algorithm would be the equation, so break it down and think about how that equation looks in code. Work out each step: 1) the value of what you would pass to sine: 360/n ...2) but, this must be converted to radians for the sin method, 3)....and so on...