Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cmath>
  5. #include <random>
  6.  
  7.  
  8. using namespace std;
  9. static mt19937 generator{random_device{}()};
  10.  
  11. double Function(double x, int key) {
  12.     if (key == 0)
  13.         return -2 * sqrt(x) * sin(0.5 * x);
  14.     else if (key == 1)
  15.         return -2 * sqrt(x) * sin(0.5 * x) * sin(5 * x);
  16. }
  17.  
  18.  
  19. void simulatedAnnealing(int key) {
  20.     double a = 2.0, b = 6.0;
  21.     auto distance = std::uniform_real_distribution<double>(a, b);
  22.     auto temp = std::uniform_real_distribution<double>(0, 1);
  23.     double xmin = distance(generator);
  24.     double tmax = 10000, tmin = 0.01;
  25.     cout << "  N         T         x         f(x)                      P         accept?" << endl;
  26.     int i = 1;
  27.     string str = "";
  28.     while (tmax > tmin) {
  29.         double Xi = distance(generator);
  30.         double difference = Function(Xi, key) - Function(xmin, key);
  31.         double probability=0.0;
  32.         str = "N";
  33.         if (difference <= 0) {
  34.             xmin = Xi;
  35.             str = "Y";
  36.             probability = 1;
  37.         }
  38.         else {
  39.             double temp1 = temp(generator);
  40.             probability = exp(-difference / tmax);
  41.             str = "N";
  42.             if (temp1 < probability) {
  43.                 xmin = Xi;
  44.                 str = "Y";
  45.             }
  46.         }
  47.         if (i < 10)
  48.             cout << "  " << i << setw(12) << std::fixed <<std::setprecision(4) <<  tmax << setw(12) << xmin << setw(12) << Function(xmin, key) << setw(20) << setprecision(3) << probability << setw(12) << str << endl;
  49.         else if (i < 100)
  50.             cout << " " << i << setw(12) << std::fixed  << std::setprecision(4) << tmax << setw(12) << xmin << setw(12) << Function(xmin, key) << setw(20) << probability << setw(12) << str << endl;
  51.         else
  52.             cout << i << setw(12) << std::fixed << std::setprecision(4) << tmax << setw(12) << xmin << setw(12) << Function(xmin, key) << setw(20) << probability << setw(12) << str << endl;
  53.         tmax *= 0.95;
  54.         i++;
  55.     }
  56.     cout << "\n\nResult: xmin: " << xmin << " ;Fmin= " << Function(xmin, key) << endl;
  57. }
  58.  
  59. int main() {
  60.     cout << "Unimodal function:" << endl;
  61.     simulatedAnnealing(0);
  62.     cout << endl << endl << "Multimodal function:" << endl;
  63.     simulatedAnnealing(1);
  64.  
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement