On 05/23/2013 11:17 PM, Mister Mak wrote:
> Thanks to Thomas and Gilles for their tips.  The univariate solution
> proposed works (for the record:
>      UnivariateFunction f = new UnivariateFunction() {public double
> value(double x) {return -(x - 5.0) * (x - 5.0) + 2.25; }};
>         BrentOptimizer optimizer = new BrentOptimizer(1e-6, 1e-12);
>         UnivariatePointValuePair solution = optimizer.optimize(new
> UnivariateObjectiveFunction(f), new MaxEval(100), GoalType.MAXIMIZE, new
> SearchInterval(-10, 10));
>         System.out.println("Min is: " + solution.getValue() + "\tobtained
> at: " + solution.getPoint());
> ).
> 
> I am now trying to maximize a function of two variables, and can't get the
> following code running:
> 
>         MultivariateFunction g =
>             new MultivariateFunction() {
>                 public double value(double[] x) {
>                     return -(x[0] - 5.0) * (x[1] - 5.0) + 2.25;
>                 }
>             };
>         SimplexOptimizer optimizerMult = new SimplexOptimizer(1e-6, 1e-12);
>         PointValuePair solutionMult = optimizerMult.optimize(new
> ObjectiveFunction(g), GoalType.MAXIMIZE, new MultiDirectionalSimplex(100));

You need to set an InitialGuess, like this:

        MultivariateFunction g = new MultivariateFunction() {
            public double value(double[] x) {
                return -(x[0] - 5.0) * (x[1] - 5.0) + 2.25;
            }
        };
        SimplexOptimizer optimizerMult = new SimplexOptimizer(1e-3, 1e-6);
        PointValuePair solutionMult = optimizerMult.optimize(
                new MaxEval(200),
                new ObjectiveFunction(g),
                GoalType.MAXIMIZE,
                new InitialGuess(new double[] {0, 0} ),
                new MultiDirectionalSimplex(2));

        System.out.println(solutionMult.getValue());
        System.out.println(Arrays.toString(solutionMult.getKey()));

But this will still not work, as a possible maximum is x[0] = -Infinity
and x[1] >= 0

I guess in your case you will have to use an optimizer which supports
bounds to get the maximum for the given function, e.g. the SimplexSolver
in the linear package.

Thomas

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscr...@commons.apache.org
For additional commands, e-mail: user-h...@commons.apache.org

Reply via email to