I'm doing a project about the unit circle and decided to code a visual representation in Java Processing, however when testing the code displays as the X value being 1 three times even though it's in the list of X values one time. Any ideas as to why?
Code:
float r = 300;
float[] xs = {1, sqrt(3/2), sqrt(2)/2, .5, 0, -.5, -sqrt(2)/2, -sqrt(3)/2, -1, -sqrt(3)/2, -sqrt(2)/2, -.5, 0, .5, sqrt(2)/2, sqrt(3/2)};
float[] ys = {0, .5, sqrt(2)/2, sqrt(3)/2, 1, sqrt(3)/2, sqrt(2)/2, .5, 0, -.5, -sqrt(2)/2, -sqrt(3)/2, -1, -sqrt(3)/2, -sqrt(2)/2, -.5};
void setup() {
size(900, 900);
background(0);
noFill();
stroke(255);
strokeWeight(4);
textAlign(CENTER, CENTER);
}
void draw() {
background(0);
translate(width / 2, height / 2);
circle(0,0,r * 2);
for (int i = 0; i < xs.length; i++) {
line(0, 0, xs[i] * r, ys[i] * r);
}
}
The reason you are getting these erroneous values (as Joop Eggen pointed out) is that you're using integer division in some of your values:
float[] xs = { ... sqrt(3/2) ... sqrt(3/2)};
Change these to the following and it should resolve your issue:
float[] xs = { ... sqrt((float) 3/2) ... sqrt((float) 3/2)};
All the other calculations perform float division, so no need to adjust them particularly. Full code with these changes applied:
float r = 300;
float[] xs = {1, sqrt((float) 3/2), sqrt(2)/2, .5, 0, -.5, -sqrt(2)/2, -sqrt(3)/2, -1, -sqrt(3)/2, -sqrt(2)/2, -.5, 0, .5, sqrt(2)/2, sqrt((float) 3/2)};
float[] ys = {0, .5, sqrt(2)/2, sqrt(3)/2, 1, sqrt(3)/2, sqrt(2)/2, .5, 0, -.5, -sqrt(2)/2, -sqrt(3)/2, -1, -sqrt(3)/2, -sqrt(2)/2, -.5};
void setup() {
size(900, 900);
background(0);
noFill();
stroke(255);
strokeWeight(4);
textAlign(CENTER, CENTER);
}
void draw() {
background(0);
translate(width / 2, height / 2);
circle(0,0,r * 2);
for (int i = 0; i < xs.length; i++) {
line(0, 0, xs[i] * r, ys[i] * r);
}
}