Java tutorial
//package com.java2s; /** A collection of machine learning utility functions. * <p> * Copyright (c) 2008 Eric Eaton * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * @author Eric Eaton (EricEaton@umbc.edu) <br> * University of Maryland Baltimore County * * @version 0.1 * */ import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class Main { /** Computes the intersection between two lines. The calculated point is approximate, * since integers are used. If you need a more precise result, use doubles everywhere. * Modified from original version (by Alexander Hristov) by Eric Eaton. * (c) 2007 Alexander Hristov. Use Freely (LGPL license). http://www.ahristov.com * * @param lineA the first line * @param lineB the second line * @return point where the segments intersect, or null if they don't */ public static Point2D intersection(Line2D lineA, Line2D lineB) { Point2D lineAPt1 = lineA.getP1(); Point2D lineAPt2 = lineA.getP2(); Point2D lineBPt1 = lineB.getP1(); Point2D lineBPt2 = lineB.getP2(); double x1 = lineAPt1.getX(); double y1 = lineAPt1.getY(); double x2 = lineAPt2.getX(); double y2 = lineAPt2.getY(); double x3 = lineBPt1.getX(); double y3 = lineBPt1.getY(); double x4 = lineBPt2.getX(); double y4 = lineBPt2.getY(); double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (d == 0) return null; double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; return new Point2D.Double(xi, yi); } }