Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Big Dave

macrumors 6502
Original poster
Nov 27, 2007
314
25
Crestview, Fl
I'm writing a simple class that will calculate the (x,y) points on a circle. I'm using the cosine and sin of the angle to calculate the points. I get strange results that I'm hoping someone can show me what I am doing wrong.
The output I get is:
1 0
0.53 0.85
-0.45 0.89
-1 0.09
-0.6 -0.8
0.37 -0.93
0.98 -0.18
0.67 0.75

The output I want is:
1 0
.71 .71
0 1
-.71 .71
-1 0
-.71 -.71
0 -1
.71 -.71

Here is my code:
Code:
import java.text.*;
import java.lang.Math;
class circle {
    public static void main (String args[]) {
    DecimalFormat df = new DecimalFormat("#.##");
      double x = 0.0;
      double y = 0.0;
      int r=1;
      for (int angle=0; angle<=315; angle+=45) {
        x = r*Math.cos(angle);
        y = r*Math.sin(angle);
        System.out.print(df.format(x));
        System.out.print(" ");
        System.out.println(df.format(y));
      }
    }
}
 
Usually needs to be in a unit called 'radians'.

One radian or π (pi) is 180˚, so there are 2π in a full circle. So use the built in value for PI in java to calculate the values you need.
 
A suggestion ... instead of iterating over the angle, specify the number of points, since otherwise you're limited to 360 in the loop.

Your loop would look like this (the compiler will optimize out 2 * Math.PI, so no need for anyone to comment on that):
Code:
        int max = 8;
        for (int i = 0; i < max; i++) {
            double radian = 2 * Math.PI * i / max;
            System.out.printf("%6.2f %6.2f\n", Math.cos(radian), Math
                    .sin(radian));
        }

Also, always use title case for class names - it's the Java style standard.
 
Thanks! You have provided me a working solution!

Thanks guys! Here is what the code is now:

Code:
import java.text.*;
import java.lang.Math;
class Circle {
    public static void main (String args[]) {
      int max =8;
      for (int i = 0; i < max; i++) {
          double radian = 2* Math.PI * i / max;
          System.out.printf("%6.2f %6.2f\n", Math.cos(radian), Math.sin(radian));
      }
    }
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.