# Thread: Trigonometry and Pi in Java

1. Member Join Date
Apr 2012
Posts
1
Rep Power
0

## 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:
Java 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.  Reply With Quote

2. Moderator  Join Date
Jul 2010
Location
California
Posts
1,638
Rep Power
12

## 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...  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•