RandomSearch.java

In [ ]:
package randomsearch;

/**
 *
 * @author ANIRUDDHA
 */

import java.util.Random;

public class RandomSearch {

    public static double f(double x){
		return x*x;
	}
	
    public static void main(String[] args) {

        Random random = new Random();
        double startPointX = 0;
        double max = f( startPointX );

		// iterate in an order to make random guesses about the maximum 
        for(int i=0;i<10000;i++){

            double point = 2*random.nextDouble();

            if( f(point) > max ){
                    max = f(point);
            }
        }

        System.out.println("Maximum is: "+max);
    }
}

Output of the program is :

Maximum is: 3.9997589690916047

You can download the complete source code here : Source Code