SlideShare uma empresa Scribd logo
Inteligência Artificial
Professor: Francisco Nauber Bernardo Gois
Inteligência
Artificial - Aula 3
1
2
Grafos e digrafos
Um objeto combinatório
conhecido como digrafo, ou grafo
dirigido, ou ainda grafo orientado.
Digrafos são importantes modelos
para uma grande variedade de
problemas de engenharia,
computação, matemática,
economia, biologia, etc.
3
Problemas de Busca
4
5
6
Busca de um caminho
7
Breadth First Search
8
package BreadthFirstSearch;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
private int data;
private boolean visited;
private List<Vertex> neighbourList;
public Vertex(int data){
this.data=data;
this.neighbourList = new ArrayList<>();
}
Vertice
9
public void addNeighbour(Vertex neighbour) {
this.neighbourList.add(neighbour);
}
@Override
public String toString() {
return ""+this.data;
}
Vertice
10
public class BreadthFirstSearch {
public void bfs(Vertex root){
Queue<Vertex> queue = new LinkedList<>();
root.setVisited(true);
queue.add(root);
while( !queue.isEmpty() ){
Vertex actualVertex = queue.remove();
System.out.print(actualVertex+" ");
for( Vertex v : actualVertex.getNeighbourList() ){
if( !v.isVisited() ){
v.setVisited(true);
queue.add(v);
}
}
}
}
}
11
public class App {
public static void main(String[] args) {
BreadthFirstSearch breadthFirstSearch = new BreadthFirstSearch();
Vertex vertex1 = new Vertex(1);
Vertex vertex2 = new Vertex(2);
Vertex vertex3 = new Vertex(3);
Vertex vertex4 = new Vertex(4);
Vertex vertex5 = new Vertex(5);
vertex1.addNeighbour(vertex2);
vertex1.addNeighbour(vertex4);
vertex4.addNeighbour(vertex5);
vertex2.addNeighbour(vertex3);
breadthFirstSearch.bfs(vertex1);
}
}
12
Deep First Search
13
private String name;
private List<Vertex> neighbourList;
private boolean visited;
private Vertex predecessor;
private int startingRank;
private int finishingRank;
public Vertex(String name) {
this.name = name;
this.neighbourList = new ArrayList<>();
}
@Override
public String toString() {
return this.name+"- StartTime: "+startingRank+"-
EndTime: "+finishingRank;
}
14
public class DepthFirstSearch {
private List<Vertex> vertexList;
private int time = 0;
public DepthFirstSearch(List<Vertex> vertexList){
this.vertexList = vertexList;
}
public void runDfs(){
for( Vertex vertex : vertexList ){
if( !vertex.isVisited() ){
dfs(vertex);
}
}
}
public void printVertices(){
for(Vertex vertex : vertexList){
System.out.println(vertex+"");
}
}
}
15
public void dfs(Vertex vertex){
System.out.print(vertex.getName()+"-");
time++;
vertex.setStartingRank(time);
for( Vertex v : vertex.getNeighbourList() ){
if( !v.isVisited() ){
v.setVisited(true);
v.setPredecessor(vertex);
dfs(v);
}
}
time++;
vertex.setFinishingRank(time);
}
16
17
18
19
20
21
22
23
24
25
26
27
Algoritmo A* (Lê-se: A-estrela) é um
algoritmo para Busca de Caminho. Ele
busca o caminho em um grafo de um vértice
inicial até um vértice final. Ele é a
combinação de aproximações heurísticas
como do algoritmo Best-first Search e da
formalidade do Algoritmo de Dijkstra.
28
29
package AStarSearch;
public class Edge {
public final double cost;
public final Node targetNode;
public Edge(Node targetNode, double cost) {
this.targetNode = targetNode;
this.cost = cost;
}
public double getCost() {
return cost;
}
public Node getTargetNode() {
return targetNode;
}
}
30
package AStarSearch;
import java.util.ArrayList;
import java.util.List;
public class Node implements Comparable<Node> {
private String value;
private double gScore;
private double fScore = 0;
private double x;
private double y;
private List<Edge> adjacenciesList;
private Node parentNode;
public Node(String value) {
this.value = value;
this.adjacenciesList = new ArrayList<>();
}
public double getgScore() {
return gScore;
}
public void addNeighbour(Edge edge){
this.adjacenciesList.add(edge);
}
31
@Override
public int compareTo(Node otherNode) {
return Double.compare(this.fScore, otherNode.getfScore());
}
32
package AStarSearch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
public class Algorithm {
public void aStarSearch(Node sourceNode, Node goalNode) {
Set<Node> exploredNodes = new HashSet<Node>();
PriorityQueue<Node> unexploredNodesQueue = new PriorityQueue<Node>();
sourceNode.setgScore(0);
unexploredNodesQueue.add(sourceNode);
boolean found = false;
while ( !unexploredNodesQueue.isEmpty() && !found ) {
Node currentNode = unexploredNodesQueue.poll();
exploredNodes.add(currentNode);
if (currentNode.getValue().equals(goalNode.getValue())) {
found = true;
}
33
for (Edge e : currentNode.getAdjacenciesList()) {
Node childNode = e.getTargetNode();
double cost = e.getCost();
double tempGScore = currentNode.getgScore() + cost;
double tempFScore = tempGScore + heuristic(childNode, goalNode);
if( exploredNodes.contains(childNode) && (tempFScore >=
childNode.getfScore()) ) {
continue;
} else if ( !unexploredNodesQueue.contains(childNode) || (tempFScore <
childNode.getfScore()) ) {
childNode.setParentNode(currentNode);
childNode.setgScore(tempGScore);
childNode.setfScore(tempFScore);
if (unexploredNodesQueue.contains(childNode)) {
unexploredNodesQueue.remove(childNode);
}
unexploredNodesQueue.add(childNode);
}
}
}
}
34
public List<Node> printPath(Node targetNode) {
List<Node> pathList = new ArrayList<Node>();
for (Node node = targetNode; node != null; node =
node.getParentNode()) {
pathList.add(node);
}
Collections.reverse(pathList);
return pathList;
}
// Manhattan heuristic/distance !!!
public double heuristic(Node node1, Node node2){
return Math.abs( node1.getX() - node2.getX() ) +
Math.abs( node2.getY() - node2.getY() );
}
MetaHeurítica
Uma meta-heurística é um método
heurístico para resolver de forma
genérica problemas de otimização
(normalmente da área de otimização
combinatória).
Metaheurísticas são geralmente
aplicadas a problemas que não se
conhece algoritmo eficiente (veja
problemas NP-completos).
35
36
37
38
39
40
package com.balazsholczer.max;
public class HillClimbing {
public static double f(double x){
return -(x-1)*(x-1)+2;
}
public static void main(String[] args) {
double dx = 0.01;
double actualPointX = -2;
double max = f( actualPointX );
while( f(actualPointX+dx) >= max){
max = f(actualPointX+dx);
System.out.println("X:"+actualPointX+" y:"+f(actualPointX));
actualPointX+=dx;
}
System.out.println("Min with hill climbing: "+max);
}
}
41
42
SIMULATED ANNEALING
43
A metaheurística usada é uma metáfora de
um processo térmico, dito annealing ou
recozimento, utilizado em metalurgia para
obtenção de estados de baixa energia num
sólido. O processo consiste de duas etapas:
na primeira, a temperatura do sólido é
aumentada para um valor próximo de 1100°C;
na segunda, o resfriamento deve ser realizado
lentamente até que o material se solidifique,
sendo acompanhado e controlado esse
arrefecimento. Nesta segunda fase,
executada lentamente, os átomos que
compõem o material organizam-se numa
estrutura uniforme com energia mínima. Isto
resulta em que os átomos desse material
ganhem energia para se movimentarem
livremente e, ao arrefecer de forma
controlada, dar-lhes uma melhor hipótese de
se organizarem numa configuração com
menor energia interna, para ter uma redução
dos defeitos do material, como resultado
prático.
44
package com.balazsholczer.sa;
public class Constants {
private Constants(){
}
public static final double MIN_COORDINATE = -2;
public static final double MAX_COORDINATE = 2;
public static final double MIN_TEMPERATURE = 1;
public static final double START_TEMPERATURE = 100;
public static final double COOLING_RATE = 0.02;
}
45
public class SimulatedAnnealing {
private Random randomGenerator;
private double currentCoordinateX;
private double nextCoordinateX;
private double bestCoordinateX;
public SimulatedAnnealing(){
this.randomGenerator = new Random();
}
46
public void findOptimum(){
double temperature = Constants.START_TEMPERATURE;
while( temperature > Constants.MIN_TEMPERATURE ){
nextCoordinateX = getRandomX();
double currentEnergy = getEnergy(currentCoordinateX);
double newEnergy = getEnergy(nextCoordinateX);
if( acceptanceProbability(currentEnergy, newEnergy, temperature) > Math.random() ){
currentCoordinateX = nextCoordinateX;
}
if( f(currentCoordinateX) < f(bestCoordinateX)){
bestCoordinateX = currentCoordinateX;
}
temperature *= 1 - Constants.COOLING_RATE;
}
System.out.println("Global extremum is: x="+bestCoordinateX + "f(x) = " + f(bestCoordinateX));
}
47
private double getRandomX() {
return randomGenerator.nextDouble()*(Constants.MAX_COORDINATE -
Constants.MIN_COORDINATE) + Constants.MIN_COORDINATE;
}
private double f(double x){
return (x-0.3)*(x-0.3)*(x-0.3)-5*x+x*x-2;
}
public double acceptanceProbability(double energy, double newEnergy, double
temperature) {
// If the new solution is better, accept it
if (newEnergy < energy) {
return 1.0;
}
// If the new solution is worse, calculate an acceptance probability
// T is small: we accept worse solutions with lower probability !!!
return Math.exp((energy - newEnergy) / temperature);
}
48
package com.balazsholczer.sa;
public class App {
public static void main(String[] args) {
SimulatedAnnealing annealing = new
SimulatedAnnealing();
annealing.findOptimum();
}
}
49
MetaHeuríticas Evolutivas ou Single Point
50
Algorítmos Genéticos
Inteligencia artificial 3
52
Sugestão
53

Mais conteúdo relacionado

PDF
Passagem de Objetos entre Java e Oracle
PDF
Sistemas infgerencial 1
PDF
Inteligencia artificial 2
PDF
Seguranca informacao 1
PDF
Sistemas operacionais 4
PDF
Sistemas operacionais 3
PDF
Inteligencia artificial 4
PDF
Sistemas infgerencial3
Passagem de Objetos entre Java e Oracle
Sistemas infgerencial 1
Inteligencia artificial 2
Seguranca informacao 1
Sistemas operacionais 4
Sistemas operacionais 3
Inteligencia artificial 4
Sistemas infgerencial3

Destaque (20)

PDF
Sistemas operacionais 2
PDF
Sist infgerencial4
PDF
Sistemas operacionais1
PDF
Inteligencia artificial 1
PDF
Testes não funcionais 2
PDF
Sistemas operacionais 5
PDF
Inteligencia artificial5
PDF
Sistema infgerenciais 2
PDF
Beefataque
PDF
Invasaocom exploits
PDF
Data science
PDF
Testes nao funcionais 1
PDF
Sistema infgerencial5
PDF
Inteligencia artifical 6
PDF
Sistemas operacionais 6
PDF
Ssit informacoesgerenciais 5
PDF
Sist operacionais 7
PDF
Inteligencia artifical 7
PDF
Padrões de Projeto
PDF
Introdução a Ciência de Dados
Sistemas operacionais 2
Sist infgerencial4
Sistemas operacionais1
Inteligencia artificial 1
Testes não funcionais 2
Sistemas operacionais 5
Inteligencia artificial5
Sistema infgerenciais 2
Beefataque
Invasaocom exploits
Data science
Testes nao funcionais 1
Sistema infgerencial5
Inteligencia artifical 6
Sistemas operacionais 6
Ssit informacoesgerenciais 5
Sist operacionais 7
Inteligencia artifical 7
Padrões de Projeto
Introdução a Ciência de Dados
Anúncio

Semelhante a Inteligencia artificial 3 (8)

PDF
Aulas 11-guloso Algoritmos
PDF
Grafos e Algoritimos - Dr. Julio Cesar de Araujo Menezes
PDF
Computação com DNA - Modelo baseado em Stickers
PDF
Caminhos Mínimos: Dijkstra e Floyd-Warshall
PDF
Treinamento para Competições de Programacão - Single-Source Shortest Paths: D...
PDF
Apresentação ia
PDF
Algoritmos aproximativos
Aulas 11-guloso Algoritmos
Grafos e Algoritimos - Dr. Julio Cesar de Araujo Menezes
Computação com DNA - Modelo baseado em Stickers
Caminhos Mínimos: Dijkstra e Floyd-Warshall
Treinamento para Competições de Programacão - Single-Source Shortest Paths: D...
Apresentação ia
Algoritmos aproximativos
Anúncio

Mais de Nauber Gois (15)

PDF
Ai health
PDF
Inteligencia artificial 13
PDF
Sistemas operacionais 14
PDF
Sistemas operacionais 13
PDF
Inteligencia artificial 12
PDF
Sistemas operacionais 12
PDF
Sistemas operacionais 11
PDF
Sistemas operacionais 10
PDF
Inteligencia artificial 11
PDF
Sistemas operacional 9
PDF
Inteligencia artificial 10
PDF
Sistemas operacionais 8
PDF
Inteligencia artificial 9
PDF
Inteligencia artificial 8
PDF
Sist infgerenciais 8
Ai health
Inteligencia artificial 13
Sistemas operacionais 14
Sistemas operacionais 13
Inteligencia artificial 12
Sistemas operacionais 12
Sistemas operacionais 11
Sistemas operacionais 10
Inteligencia artificial 11
Sistemas operacional 9
Inteligencia artificial 10
Sistemas operacionais 8
Inteligencia artificial 9
Inteligencia artificial 8
Sist infgerenciais 8

Último (11)

PDF
Termos utilizados na designação de relação entre pessoa e uma obra.pdf
PPTX
Como-se-implementa-um-softwareeeeeeeeeeeeeeeeeeeeeeeee.pptx
PPTX
Viasol Energia Solar -Soluções para geração e economia de energia
PPTX
Mecânico de Manutenção de Equipamentos.pptx
PPTX
Eng. Software - pontos essenciais para o início
PDF
Manejo integrado de pragas na cultura do algodão
PPTX
Informática Aplicada Informática Aplicada Plano de Ensino - estudo de caso NR...
PDF
eBook - GUIA DE CONSULTA RAPIDA EM ROTEADORES E SWITCHES CISCO - VOL I.pdf
PPTX
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
PPTX
Utilizando code blockes por andre backes
PPTX
Arquitetura de computadores - Memórias Secundárias
Termos utilizados na designação de relação entre pessoa e uma obra.pdf
Como-se-implementa-um-softwareeeeeeeeeeeeeeeeeeeeeeeee.pptx
Viasol Energia Solar -Soluções para geração e economia de energia
Mecânico de Manutenção de Equipamentos.pptx
Eng. Software - pontos essenciais para o início
Manejo integrado de pragas na cultura do algodão
Informática Aplicada Informática Aplicada Plano de Ensino - estudo de caso NR...
eBook - GUIA DE CONSULTA RAPIDA EM ROTEADORES E SWITCHES CISCO - VOL I.pdf
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
Utilizando code blockes por andre backes
Arquitetura de computadores - Memórias Secundárias

Inteligencia artificial 3

  • 1. Inteligência Artificial Professor: Francisco Nauber Bernardo Gois Inteligência Artificial - Aula 3 1
  • 2. 2 Grafos e digrafos Um objeto combinatório conhecido como digrafo, ou grafo dirigido, ou ainda grafo orientado. Digrafos são importantes modelos para uma grande variedade de problemas de engenharia, computação, matemática, economia, biologia, etc.
  • 4. 4
  • 5. 5
  • 6. 6 Busca de um caminho
  • 8. 8 package BreadthFirstSearch; import java.util.ArrayList; import java.util.List; public class Vertex { private int data; private boolean visited; private List<Vertex> neighbourList; public Vertex(int data){ this.data=data; this.neighbourList = new ArrayList<>(); } Vertice
  • 9. 9 public void addNeighbour(Vertex neighbour) { this.neighbourList.add(neighbour); } @Override public String toString() { return ""+this.data; } Vertice
  • 10. 10 public class BreadthFirstSearch { public void bfs(Vertex root){ Queue<Vertex> queue = new LinkedList<>(); root.setVisited(true); queue.add(root); while( !queue.isEmpty() ){ Vertex actualVertex = queue.remove(); System.out.print(actualVertex+" "); for( Vertex v : actualVertex.getNeighbourList() ){ if( !v.isVisited() ){ v.setVisited(true); queue.add(v); } } } } }
  • 11. 11 public class App { public static void main(String[] args) { BreadthFirstSearch breadthFirstSearch = new BreadthFirstSearch(); Vertex vertex1 = new Vertex(1); Vertex vertex2 = new Vertex(2); Vertex vertex3 = new Vertex(3); Vertex vertex4 = new Vertex(4); Vertex vertex5 = new Vertex(5); vertex1.addNeighbour(vertex2); vertex1.addNeighbour(vertex4); vertex4.addNeighbour(vertex5); vertex2.addNeighbour(vertex3); breadthFirstSearch.bfs(vertex1); } }
  • 13. 13 private String name; private List<Vertex> neighbourList; private boolean visited; private Vertex predecessor; private int startingRank; private int finishingRank; public Vertex(String name) { this.name = name; this.neighbourList = new ArrayList<>(); } @Override public String toString() { return this.name+"- StartTime: "+startingRank+"- EndTime: "+finishingRank; }
  • 14. 14 public class DepthFirstSearch { private List<Vertex> vertexList; private int time = 0; public DepthFirstSearch(List<Vertex> vertexList){ this.vertexList = vertexList; } public void runDfs(){ for( Vertex vertex : vertexList ){ if( !vertex.isVisited() ){ dfs(vertex); } } } public void printVertices(){ for(Vertex vertex : vertexList){ System.out.println(vertex+""); } } }
  • 15. 15 public void dfs(Vertex vertex){ System.out.print(vertex.getName()+"-"); time++; vertex.setStartingRank(time); for( Vertex v : vertex.getNeighbourList() ){ if( !v.isVisited() ){ v.setVisited(true); v.setPredecessor(vertex); dfs(v); } } time++; vertex.setFinishingRank(time); }
  • 16. 16
  • 17. 17
  • 18. 18
  • 19. 19
  • 20. 20
  • 21. 21
  • 22. 22
  • 23. 23
  • 24. 24
  • 25. 25
  • 26. 26
  • 27. 27 Algoritmo A* (Lê-se: A-estrela) é um algoritmo para Busca de Caminho. Ele busca o caminho em um grafo de um vértice inicial até um vértice final. Ele é a combinação de aproximações heurísticas como do algoritmo Best-first Search e da formalidade do Algoritmo de Dijkstra.
  • 28. 28
  • 29. 29 package AStarSearch; public class Edge { public final double cost; public final Node targetNode; public Edge(Node targetNode, double cost) { this.targetNode = targetNode; this.cost = cost; } public double getCost() { return cost; } public Node getTargetNode() { return targetNode; } }
  • 30. 30 package AStarSearch; import java.util.ArrayList; import java.util.List; public class Node implements Comparable<Node> { private String value; private double gScore; private double fScore = 0; private double x; private double y; private List<Edge> adjacenciesList; private Node parentNode; public Node(String value) { this.value = value; this.adjacenciesList = new ArrayList<>(); } public double getgScore() { return gScore; } public void addNeighbour(Edge edge){ this.adjacenciesList.add(edge); }
  • 31. 31 @Override public int compareTo(Node otherNode) { return Double.compare(this.fScore, otherNode.getfScore()); }
  • 32. 32 package AStarSearch; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; public class Algorithm { public void aStarSearch(Node sourceNode, Node goalNode) { Set<Node> exploredNodes = new HashSet<Node>(); PriorityQueue<Node> unexploredNodesQueue = new PriorityQueue<Node>(); sourceNode.setgScore(0); unexploredNodesQueue.add(sourceNode); boolean found = false; while ( !unexploredNodesQueue.isEmpty() && !found ) { Node currentNode = unexploredNodesQueue.poll(); exploredNodes.add(currentNode); if (currentNode.getValue().equals(goalNode.getValue())) { found = true; }
  • 33. 33 for (Edge e : currentNode.getAdjacenciesList()) { Node childNode = e.getTargetNode(); double cost = e.getCost(); double tempGScore = currentNode.getgScore() + cost; double tempFScore = tempGScore + heuristic(childNode, goalNode); if( exploredNodes.contains(childNode) && (tempFScore >= childNode.getfScore()) ) { continue; } else if ( !unexploredNodesQueue.contains(childNode) || (tempFScore < childNode.getfScore()) ) { childNode.setParentNode(currentNode); childNode.setgScore(tempGScore); childNode.setfScore(tempFScore); if (unexploredNodesQueue.contains(childNode)) { unexploredNodesQueue.remove(childNode); } unexploredNodesQueue.add(childNode); } } } }
  • 34. 34 public List<Node> printPath(Node targetNode) { List<Node> pathList = new ArrayList<Node>(); for (Node node = targetNode; node != null; node = node.getParentNode()) { pathList.add(node); } Collections.reverse(pathList); return pathList; } // Manhattan heuristic/distance !!! public double heuristic(Node node1, Node node2){ return Math.abs( node1.getX() - node2.getX() ) + Math.abs( node2.getY() - node2.getY() ); }
  • 35. MetaHeurítica Uma meta-heurística é um método heurístico para resolver de forma genérica problemas de otimização (normalmente da área de otimização combinatória). Metaheurísticas são geralmente aplicadas a problemas que não se conhece algoritmo eficiente (veja problemas NP-completos). 35
  • 36. 36
  • 37. 37
  • 38. 38
  • 39. 39
  • 40. 40 package com.balazsholczer.max; public class HillClimbing { public static double f(double x){ return -(x-1)*(x-1)+2; } public static void main(String[] args) { double dx = 0.01; double actualPointX = -2; double max = f( actualPointX ); while( f(actualPointX+dx) >= max){ max = f(actualPointX+dx); System.out.println("X:"+actualPointX+" y:"+f(actualPointX)); actualPointX+=dx; } System.out.println("Min with hill climbing: "+max); } }
  • 41. 41
  • 43. 43 A metaheurística usada é uma metáfora de um processo térmico, dito annealing ou recozimento, utilizado em metalurgia para obtenção de estados de baixa energia num sólido. O processo consiste de duas etapas: na primeira, a temperatura do sólido é aumentada para um valor próximo de 1100°C; na segunda, o resfriamento deve ser realizado lentamente até que o material se solidifique, sendo acompanhado e controlado esse arrefecimento. Nesta segunda fase, executada lentamente, os átomos que compõem o material organizam-se numa estrutura uniforme com energia mínima. Isto resulta em que os átomos desse material ganhem energia para se movimentarem livremente e, ao arrefecer de forma controlada, dar-lhes uma melhor hipótese de se organizarem numa configuração com menor energia interna, para ter uma redução dos defeitos do material, como resultado prático.
  • 44. 44 package com.balazsholczer.sa; public class Constants { private Constants(){ } public static final double MIN_COORDINATE = -2; public static final double MAX_COORDINATE = 2; public static final double MIN_TEMPERATURE = 1; public static final double START_TEMPERATURE = 100; public static final double COOLING_RATE = 0.02; }
  • 45. 45 public class SimulatedAnnealing { private Random randomGenerator; private double currentCoordinateX; private double nextCoordinateX; private double bestCoordinateX; public SimulatedAnnealing(){ this.randomGenerator = new Random(); }
  • 46. 46 public void findOptimum(){ double temperature = Constants.START_TEMPERATURE; while( temperature > Constants.MIN_TEMPERATURE ){ nextCoordinateX = getRandomX(); double currentEnergy = getEnergy(currentCoordinateX); double newEnergy = getEnergy(nextCoordinateX); if( acceptanceProbability(currentEnergy, newEnergy, temperature) > Math.random() ){ currentCoordinateX = nextCoordinateX; } if( f(currentCoordinateX) < f(bestCoordinateX)){ bestCoordinateX = currentCoordinateX; } temperature *= 1 - Constants.COOLING_RATE; } System.out.println("Global extremum is: x="+bestCoordinateX + "f(x) = " + f(bestCoordinateX)); }
  • 47. 47 private double getRandomX() { return randomGenerator.nextDouble()*(Constants.MAX_COORDINATE - Constants.MIN_COORDINATE) + Constants.MIN_COORDINATE; } private double f(double x){ return (x-0.3)*(x-0.3)*(x-0.3)-5*x+x*x-2; } public double acceptanceProbability(double energy, double newEnergy, double temperature) { // If the new solution is better, accept it if (newEnergy < energy) { return 1.0; } // If the new solution is worse, calculate an acceptance probability // T is small: we accept worse solutions with lower probability !!! return Math.exp((energy - newEnergy) / temperature); }
  • 48. 48 package com.balazsholczer.sa; public class App { public static void main(String[] args) { SimulatedAnnealing annealing = new SimulatedAnnealing(); annealing.findOptimum(); } }
  • 53. 53