Created
June 19, 2020 14:00
-
-
Save d4em0n/07679e81b56eb4d0934c2fdad404a2b8 to your computer and use it in GitHub Desktop.
hill climbing java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Math; | |
import java.util.ArrayList; | |
class Point { | |
public double x; | |
public double y; | |
public Point(double x, double y) { | |
this.x = x; | |
this.y = y; | |
} | |
} | |
class PointHill { | |
public ArrayList<Point> points; | |
private double pow2(double x) { | |
return x*x; | |
} | |
private double dx_distance(double x1,double y1,double x2,double y2) { | |
return (x1-x2)/Math.sqrt(pow2(x1-x2) + pow2(y1-y2)); | |
} | |
private double dy_distance(double x1, double y1, double x2, double y2) { | |
return (y1-y2)/Math.sqrt(pow2(x1-x2) + pow2(y1-y2)); | |
} | |
private Point dxdy_distance(double x1,double y1,double x2,double y2) { | |
Point d = new Point(this.dx_distance(x1,y1,x2,y2), this.dy_distance(x1,y1,x2,y2)); | |
return d; | |
} | |
private double distance(double x1,double y1,double x2,double y2) { | |
return Math.sqrt(pow2((x1-x2)) + pow2((y1-y2))); | |
} | |
private Point calc_deriv_score(Point point) { | |
Point[] points = this.points.toArray(new Point[this.points.size()]); | |
double x = point.x; | |
double y = point.y; | |
double dx = 0; | |
double dy = 0; | |
double xa,ya; | |
Point di; | |
for(int i=0; i<points.length; i++) { | |
xa = points[i].x; | |
ya = points[i].y; | |
di = dxdy_distance(x,y,xa,ya); | |
dx += di.x; | |
dy += di.y; | |
} | |
return new Point(dx, dy); | |
} | |
public Point get_result() { | |
Point start = new Point(0,0); | |
int eps = 100; | |
double lr = 0.1; | |
Point d; | |
for(int i=0;i < eps; i++) { | |
d = this.calc_deriv_score(start); | |
start.x -= d.x * lr; | |
start.y -= d.y * lr; | |
} | |
return start; | |
} | |
public PointHill() { | |
this.points = new ArrayList<Point>(); | |
} | |
public void addPoint(double x, double y) { | |
this.points.add(new Point(x,y)); | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
Point result; | |
PointHill hill = new PointHill(); | |
hill.addPoint(2,2); // tambah titik koordinat 2,2 | |
hill.addPoint(3,4); // tambah titik koordinat 3,4 | |
hill.addPoint(4,2); // tambah titik koordinat 4,2 | |
hill.addPoint(5,4); // tambah titik koordinat 5,4 | |
result = hill.get_result(); // hitung titik optimum | |
System.out.println("X = "+result.x+"; Y = "+result.y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment