I am trying to find the point of intersection of a circle and a line through its center. I want to put an arrow on the point actually, to make a directed graph. After some calculations, I found that the math that would go in is,

formula

The figure of reference is:
intersection

The code I am using to achieve this is:

private Point getArrow(Point center, Point line) {
        Point interesection;
        int a = line.x;
        int b = center.x;
        int c = line.y;
        int d = center.y;
        int x1 = 0, y1 = 0, x2 = 0, y2 = 0;

        if ((b - a) != 0) {
            try {
                x1 = (int) (b + ((20 * (a - b)) / Math.sqrt((Math.pow((a - b), 2)) + Math.pow(c - d, 2))));
                x2 = (int) (b - ((20 * (a - b)) / Math.sqrt((Math.pow((a - b), 2)) + Math.pow(c - d, 2))));

                y1 = (int) (((d - c) / (b - a)) * (x1 - a) + c);
                y2 = (int) (((d - c) / (b - a)) * (x2 - a) + c);
            } catch (ArithmeticException ex) {
                if ((a - b) == 0) {
                    y1 = y2 = 0;
                } else if ((a - b) == 0 && (c - d) == 0) {
                    x1 = x2 = y1 = y2 = 0;
                }
            }
        } else {
            return new Point(center.x+19, center.y - 5);
        }
        Point p1 = new Point(x1+19, y1+19);
        Point p2 = new Point(x2+19, y2+19);

        if (line.distanceSq(p2) < line.distanceSq(p1)) {
            interesection = new Point(p2);
        } else {
            interesection = new Point(p1);
        }


        return interesection;
    }

Can anyone tell me why my code is breaking for the math? I am trying to plot the point returned as a filled oval of width and height being 5. The radius of the original circle is 20.

Edited 4 Years Ago by sid78669: Forgot to mention that the radius (r) is 20.

This is very confusing because the variable names in your code look like the ones in the diagram/formulae, but are used completely differently -eg in the diagram x2,y2 is the centre of the circle, but in your code they are one of the intersection points. So my advice is
1. Make yur variables names match exactly the reference diagram/formulae
2. Forget about the filled oval for now and just get it returning the intersection point correctly
and by the way...
3. Don't use try/catch for predictable arithmetic exceptions; exceptions should be used for exceptional events that you can't predict - test the data so that the exception won't be thrown in the first place

This article has been dead for over six months. Start a new discussion instead.