简体   繁体   中英

Plotting Points on Circle

I was playing around in java and was trying to create my own version of the point class:

public class Location {
    public double x, y;

    public Location(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double dist(Location location) {
        return Math.sqrt(Math.pow(location.x - x, 2) + Math.pow(location.y - y, 2));
    }

    //Rotates the point the amount in angle around the point center
    public void rotate(Location center, double angle) {
        //Also tried this
        /*double current = Math.atan2(center.y - y, center.x - x);
        x = center.x + (Math.cos(current + angle) * dist(center));
        y = center.y + (Math.sin(current + angle) * dist(center));*/
        //Current code
        x = center.x + (Math.cos(angle) * dist(center));
        y = center.y + (Math.sin(angle) * dist(center));
    }
}

However, no matter what I try, the data returned by the rotate() function is slightly off. Instead of a perfect circle, this function outputs a strange deflated shape.

public class Circle {

    //Should output circle
    public static void main(String[] args) {
        for (int i = 0; i < 18; i++) {
            Location point = new Location(100, 100);
            point.rotate(new Location(200, 200), Math.toRadians(i * 20));
            System.out.print("(" + point.x + ", " + point.y + ")");
        }
    }
}

When I outputted these coordinates to this plotting site this is the image I get: 不是圆形的怪异形状

My math is identical to Java: Plotting points uniformly on a circle using Graphics2d so I don't know what is going on.

Calculate dist(center) once, store it in a variable, then use that variable in updating x and y :

double d = dist(center);
x = center.x + (Math.cos(angle) * d);
y = center.y + (Math.sin(angle) * d);

dist(center) depends upon x , so you get a different value after updating x when calculating the new value of y .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM