Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//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.Point2D;

public class Main {
    /** Does linear interpolation at x of the line from pt1 to pt2.
     * @param pt1 one endpoint of the line.
     * @param pt2 another endpoint of the line.
     * @param x the x-coordinate of the interpolated point.
     * @return the desired interpolated point.
     */
    public static Point2D interpolate(Point2D pt1, Point2D pt2, double x) {
        double slope = (pt2.getY() - pt1.getY()) / (pt2.getX() - pt1.getX());
        double y = pt1.getY() + (x - pt1.getX()) * slope;
        return new Point2D.Double(x, y);
    }

    /** Interpolates the given x onto the line of points.
     * @param points
     * @param x
     * @return x interpolated onto the line defined by the points
     */
    public static Point2D interpolate(Point2D[] points, double x) {
        // determine the two point boundaries for the line segment
        for (int i = 0; i < points.length - 1; i++) {
            Point2D pt1 = points[i];
            Point2D pt2 = points[i + 1];
            if (x == pt1.getX())
                return new Point2D.Double(pt1.getX(), pt1.getY());
            else if (x < pt2.getX())
                return interpolate(pt1, pt2, x);
        }

        // if we reach here, then x >= the last point
        Point2D pt1 = points[points.length - 2];
        Point2D pt2 = points[points.length - 1];
        if (x == pt2.getX())
            return new Point2D.Double(pt2.getX(), pt2.getY());
        else
            return interpolate(pt1, pt2, x);
    }
}