3

Could anyone show me a sample code to use NelderMeadSolver class in F#?

For example, I want to minimize the following function: F(X, Y)

F = (X-1)^2 + (y-1)^2 where 0< X < 2 , 0< Y < 2 Answer is obviousely X = 1, Y = 1

I found an example for C#:
http://msdn.microsoft.com/en-us/library/hh404040(v=VS.93).aspx

I would appreciate very much if someone can give me simple F# code to minimize the function above. Thank you.

convexky
  • 43
  • 5

1 Answers1

4

I've never used Solver Foundation before, but here is a straightforward translation from C# example in MSDN (adapted to your optimization function):

open System
open Microsoft.SolverFoundation.Common
open Microsoft.SolverFoundation.Solvers

let xInitial = [| 0.; 0. |]
let xLower = [| 0.; 0. |]
let xUpper = [| 2.; 2. |]

let sqr x = x * x

let solution = 
   NelderMeadSolver.Solve(
      Func<float [], _>(fun xs -> sqr(xs.[0] - 1.) + sqr(xs.[1] - 1.)), 
      xInitial, xLower, xUpper)

printfn "%A" solution.Result
printfn "solution = %A" (solution.GetSolutionValue 0)
printfn "x = %A" (solution.GetValue 1)
printfn "y = %A" (solution.GetValue 2)

You should be able to add Solver Foundation's references and build the program. If you use the code in F# Interactive, remember to add Solver Foundation's dll files by referencing their exact paths.

pad
  • 41,040
  • 7
  • 92
  • 166
  • Thank you. I managed to reference the SolverFoundation and retargeted the .net framework 4. But I am afraid that I can't compile the code above using VS 11. I think I have to instantiate the NelderMeadSolver class first. For example, let NMSolver = new NelderMeadSolver() and then let solution = NMSolver.Solver ( .....) Here is the link for the class : http://msdn.microsoft.com/en-us/library/microsoft.solverfoundation.solvers.neldermeadsolver(v=vs.93).aspx – convexky Feb 19 '12 at 20:15
  • What is the error? According to your link `NelderMeadSolver.Solve` is a static method, so you don't have to instantiate an object to use the solver. – pad Feb 19 '12 at 20:59
  • It has an error on the line let solution = NelderMeadSolver.Solve( ...) saying that "the member or object constructor 'Solve' does not take 1 argument(s). An overload was found taking 2 arguments. It seems that Solve method doesn't have one to one match with its C# couterpart. The link above gives some info regarding the arguments. But I don't know how to implement it. Thank you!! – convexky Feb 19 '12 at 21:12
  • It seems that the first argument should be the Func(T,Tresult) Delegate. Could you guide me what the syntax for the Func Delegate? http://msdn.microsoft.com/en-us/library/bb549151.aspx#Y0 – convexky Feb 19 '12 at 21:28
  • Yes, I have fixed the example using delegate. The program should compile fine now. – pad Feb 19 '12 at 21:49