When researching intelligent algorithms in the previous paragraph, it was found that if implemented using Java, the implementation process is almost the same, but the adaptive value function is based on
The difference between the subjects of the study changed greatly, which hindered the maintenance of the Code, and a question arose: could the appropriate The value function
as a parameter passed in to the method, according to the habit of C + +, because of the presence of pointers, the function can be passed as a pointer, because the complex use of pointers
and difficult to maintain, the effect of the general. If you want to change an object-oriented idea, you can design an interface I, which provides only one method, then the phase
when the interface can be passed as a parameter into the method, the call only need to design a class, implement interface I, then you can The function is passed into the method.
The following 0.618 gold search for example, because the objective function of different, to meet the above described, note that this search can only be a single-peak function is feasible,
The algorithm looks like this:
1. First create an interface that has only one method to fit the value:
Public Interface Fitness { publicdouble getfitness (double X);}
2. Create a class that simply implements the above 0.618 search methods:
stationutils{
/*** * Golden Section Search method, find the function of minimum value *@parammin Search Limit *@paramMax Search Lower limit *@paramFitness Function Value *@return */ Public DoubleGoldensearch (DoubleMinDoublemax,fitness Fitness) { /*double x1=min+0.382* (max-min);*/ DoubleA=doubleoperation.substract (max,min); DoubleX1=doubleoperation.add (Min,doubleoperation.multiply (0.382, a)); /*double x2=min+0.618* (max-min);*/ DoubleX2=doubleoperation.add (Min,doubleoperation.multiply (0.618, a)); Doublef1=fitness.getfitness (X1); DoubleF2=fitness.getfitness (X2); while(Math.Abs (Doubleoperation.substract (x1,x2)) >delt) { if(f1<F2) {Max=X2; X2=X1; F2=F1; X1=min+0.382* (max-min); F1=fitness.getfitness (X1); }Else{min=X1; X1=X2; F1=F2; X2=min+0.618* (max-min); F2=fitness.getfitness (X2); } } returnDoubleoperation.divide (Doubleoperation.add (max,min), 2); }
}
3. Create a class to implement the fitness interface, that is, to write your own target function, and here is an example of a unary two-time function:
Public class Implements fitness{ @Override publicdouble getfitness (double X) { return x*x-3 * X + 1; } }
4. Simply call:
@Test Public void run1 () { func func=new Func (); double Result=stationutils.goldensearch ( -2.00,4.00, func); SYSTEM.OUT.PRINTLN (result); }
Summary, the addition of the parameters to pass more, you can pass the value into the interface implementation class, then getfitness this method can access this parameter
How Java takes a method as a parameter-polymorphic