* We generate random numbers: the indexes where we evaluate the function.
* We store a reference to the maximum element: i.e we keep checking whether the generated index f(x) > max or not.
* It does not gives the best solution always. hence we have to rely on a good guess close to the actual solution.

Codes of the Java files included in the program are given below:

StochasticSearch.java

In [ ]:
package stochasticsearch;

import java.util.Random;

/**
 *
 * @author ANIRUDDHA
 */
public class StochasticSearch {

    // The function whose max/min is to be found
    public static double func(double x){
        return -(x-1)*(x-1)+2;
    }
    
    public static void main(String[] args) {
        
        // Stochastic Search doesnt iterate in an order, 
		// it makes random guesses about the maximum 
		// and stores them as a reference for comparison.
        Random rand = new Random();
        double startPointX = 0;
        double max = func(startPointX);
        
        //Make 1000 iterations
        for(int i=0;i<1000;i++){
            
            double index = 2*rand.nextDouble();
            if(func(index) > max){
                max = func(index);
            }
        }
        
        System.out.println("Maximum value y=f(x) is "+max);
    }
    
    
}

Output of the program is :

Maximum value y=f(x) is 1.9999930084758073

You can download the complete source code here : Source Code