Explore Courses Blog Tutorials Interview Questions
0 votes
in AI and Deep Learning by (50.2k points)

Thanks for all your help and sharing.

My question is in regards to the Stochastic Search. This technique is used to do approximations of data through a defined amount of circles over a, in general, mathematical calculation. Please see the following code, I tried to reduce it to its minimum. I expect to have this code set up as a lambda expression, the for loop, I would like to have the best performance of it. I have some intents but I'm not sure if I got the most of it.

package stochasticsearch;

import java.util.Random;

public class StochasticSearch {

    public static double f(double x) {

        return -(x - 1) * (x - 1) + 2;


    public static void main(String[] args) {

        final Random random = new Random();

        double startPointX = 0;

        double max = f(startPointX);

        long begin = System.currentTimeMillis();

        for (int a = 0; a < 1000000000; a++) {

            double index = 2 * random.nextDouble();

            if (f(index) > max) {

                Max = f(index);



        System.out.println("Elapsed time: " + (System.currentTimeMillis() - begin));

        System.out.println("Maximum value y=f(x) is " + max);



Thanks, have a nice day.

1 Answer

0 votes
by (108k points)

Here are some mistakes that I have found in your implementation:

  1. You're applying Random when you could be using ThreadLocalRandom instead; this switch results in a relatively-large speedup.

  2. You're calculating f(index) twice inside your for-loop in certain cases when it should only be computed once per iteration.

  3. Because you're iterating over a large range of values, you could utilize a parallel stream instead; this results in a relatively-large speedup as well.

  4. You're adding 2 to every result in f, so it's better to add it a single time once the max has been calculated.

If you are looking to learn more about Artificial Intelligence then you visit Artificial Intelligence(AI) Tutorial. Also, if you are appearing for job profiles of AI Engineer or AI Expert then you can prepare for the interviews on Artificial Intelligence Interview Questions.

Browse Categories