lundi 18 mai 2015

Random Search Stochastic algorithm cannot find minimum

I try to write a c++ program for random search algorithm, but it gives me the "minimum" as [2, 2] everytime I run it for the function f(x,y) = x^2 + y^2;

the code is:

#include<iostream>
using namespace std;
#include<conio.h>
#include<stdlib.h>
double min[2], est[2];

double f(double x, double y){
    return x*x+y*y;
}

//rand() % 

void random_search(double a, double b, double c, double d, int N){          
    double min[2], est[2];
    double randIn1 = (rand() %2 )* (b-a) + a; 
    double randIn2 = (rand() %2) * (d-c) + c;
    cout<<randIn1<<endl;
    cout<<randIn2<<endl;
    min[0] = randIn1;
    cout<<min[0];
    min[1] = randIn2;
    int i;
    for (i=0;i<N;i++)
    double randNN1 = (rand() % 2) * (b-a) + a;
    double randNN2 = (rand() % 2) * (d-c) + c;
    est[0] = randNN1;
    est[1] = randNN2;
    if ( f(est[0], est[1]) < f(min[0], min[1]) )
    {
        min[0] = est[0];
        min[1] = est[1];    
    }
    cout<< min[0]<<" "<<min[1]; 
}

int main(void){
    double a = -2;
    double b = 2;
    double c = -2;
    double d = 2;
    int N = 20;
        random_search(a, b, c, d, N);

    getch();
    return 0;
}

where a,b and c,d are the boundaries of the intervals.

Please help me figure what might be wrong. By rand() %2 I want to generate random numbers between [0,1]...




Aucun commentaire:

Enregistrer un commentaire