0

我正在计算java中某些点的几何中位数。(x,y)要计算Geometric median,首先我要计算centroid所有点,然后centroid用它来计算Geometric median。我的代码工作正常,但有时它会进入无限循环(我认为。)。问题在于我的while情况。这个while条件应该根据输入点改变,但我不知道怎么做。下面我放完整的代码。

import java.util.ArrayList;

public class GeometricMedian {

    private static ArrayList<Point> points = new ArrayList<Point>();

    private class Point {
        private double x;
        private double y;

        Point(double a, double b) {
            x = a;
            y = b;
        }
    }

    public static void main(String[] args) {
        GeometricMedian gm = new GeometricMedian();
        gm.addPoints();
        Point centroid = gm.getCentroid();
        Point geoMedian = gm.getGeoMedian(centroid);
        System.out.println("GeometricMedian= {" + (float) geoMedian.x + ", "
                + (float) geoMedian.y + "}");
    }

    public void addPoints() {
        points.add(new Point(0, 1));
        points.add(new Point(2, 5));
        points.add(new Point(3, 1));
        points.add(new Point(4, 0));
    }

    public Point getCentroid() {
        double cx = 0.0D;
        double cy = 0.0D;
        for (int i = 0; i < points.size(); i++) {
            Point pt = points.get(i);
            cx += pt.x;
            cy += pt.y;
        }
        return new Point(cx / points.size(), cy / points.size());
    }

    public Point getGeoMedian(Point start) {
        double cx = 0;
        double cy = 0;

        double centroidx = start.x;
        double centroidy = start.y;
        do {
            double totalWeight = 0;
            for (int i = 0; i < points.size(); i++) {
                Point pt = points.get(i);
                double weight = 1 / distance(pt.x, pt.y, centroidx, centroidy);
                cx += pt.x * weight;
                cy += pt.y * weight;
                totalWeight += weight;
            }
            cx /= totalWeight;
            cy /= totalWeight;
        } while (Math.abs(cx - centroidx) > 0.5
                || Math.abs(cy - centroidy) > 0.5);// Probably this condition
                                                    // needs to change

        return new Point(cx, cy);
    }

    private static double distance(double x1, double y1, double x2, double y2) {
        x1 -= x2;
        y1 -= y2;
        return Math.sqrt(x1 * x1 + y1 * y1);
    }
}

请帮我修复这个错误,如果有更好的方法来计算Geometric median一些 2D 点,请写在这里。谢谢你。

4

2 回答 2

0

我不明白为什么你需要两个循环。您只需要遍历所有点。在您看来,另一个原因是什么?

于 2012-04-15T13:08:47.930 回答
0

解决此问题的一种方法是迭代一定次数。这类似于 K-Means 方法,它要么收敛到特定阈值,要么在预定义的迭代次数后停止。

于 2013-01-25T02:17:03.600 回答