Simple application of genetic algorithm-solving equations

Source: Internet
Author: User

The first genetic algorithm tells the basic idea of genetic algorithm, this blog uses genetic algorithm to solve the equation.

The following are specific:

Solution of Equation-x^3+7*x+13=0 in [3,4] interval, solution accurate to 0.001, crossover probability 0.7

Mutation probability 0.01, iteration number 100, character encoding length 10 (binary encoding)

Let's start with a simple analysis:

1. Encoding and decoding

The topic requires the use of binary encoding method to achieve, since it has been encoded, the natural need to decode, given the 10

Bit binary encoding representation of the interval range is 0~1023, the topic of the interval is [3,4] it is natural to think of the 10-bit binary

The 0 representation in the encoding is that the 3,1023 in [3,4] represents 4 in [3,4], so each binary corresponds to the

The decimal is ((10-bit binary corresponding decimal number/1023) +3), this is decoded in the interval [3,4] in the specific value.

2. Fitness function

The fitness function taken here is the reciprocal of the absolute value of the equation, i.e. f=1/(|-x^3+7*x+13|)

3. Select operator

Determine the selection ratio, using the roulette algorithm.

        /// <summary>        ///Simulation Roulette Selection Algorithm///ideas: 1. The sum of the degree of adaptability; 2. Calculate the proportion of each individual's fitness (except the first one, the others are superimposed); ///3. A random number is generated in the 0~1, and the interval of the random number is the individual to be selected/// </summary>        /// <returns>Select a good individual</returns>        Staticlist<int> RWS (list<Double>list) {List<int>Select=Newlist<int>(); List<Double> P =Newlist<Double>(); Doublesum = list. Sum ()/*The sum of the degree of adaptability*/, temp =0/*Temp Variable*/; foreach(varIteminchlist) {Temp+ = (item/sum);//OverlayP.add (temp);//probability            }            intI, J;  for(i =0; i < P.count; i++) {Temp= Rd. Nextdouble ();//random number of 0~1                 for(j =0; J < P.count; J + +)                {                    if(J = =0&& Temp < p[0])                    {                        Select. ADD (0); }                    Else if(Temp < P[J] && temp >= p[j-1])                    {                        Select.                    Add (j); }                }            }                       return Select; }    
View Code

4. Mating operator

Randomly produces mating bits, exchanging part of the genes of two chromosomes.

        /// <summary>        ///the change of the individual in the cross process (substitution of characters)/// </summary>        /// <param name= "dic" >two individuals involved in the crossover</param>        /// <param name= "Geti1" >individual 1</param>        /// <param name= "Geti2" >Individual 2</param>        /// <returns></returns>        Staticlist<string> Crossover_replace (dictionary<int,int> DiC,stringGETI1,stringGeti2) {            intIndexDoublep; List<string> Tmp_group =Newlist<string> ();//storing the individual after crossing            foreach(varIteminchdic) {p=Rd.                Nextdouble (); if(P <= crossover_probability)//probability is less than 0.7 to cross{Index= Rd. Next (0,8); Geti1= Group[item. Key];//two individuals to crossGeti2 =Group[item.                    Value]; //implementation of the crossoverTmp_group. ADD (geti1. Insert (geti1. Length, Geti2. Substring (index)). Remove (Index, Str_length-index)); Tmp_group. ADD (Geti2. Insert (Geti2. Length, Geti1. Substring (index)). Remove (index, Str_length-index)); }                Else{Tmp_group. ADD (Group[item.                    Key]); Tmp_group. ADD (Group[item.                Value]); }            }            returnTmp_group; }
View Code

5. Mutation operator

Transform the value of the chromosome gene, that is, the 0-1,1-0 transformation.

        /// <summary>        ///individual changes in the mutation process (0->1,1->0)///idea: 1. Convert individual codes into characters; 2. Generate a 0~1 random number for each character to determine if a mutation operation is needed///3. To mutate, the 0->1,1->0 will be/// </summary>        /// <param name= "str" >individual (binary code)</param>        /// <param name= "Result" >the result after the mutation</param>        /// <param name= "probability" >mutation Probability</param>        /// <returns></returns>        Static stringMutation_replace (stringStrstringResultDoubleprobability) {            Char[] Chrarray =Str.            ToCharArray ();  for(inti =0; I < Chrarray.count (); i++)            {                //less than probability, substitution character                if(Rd. Nextdouble () <=probability) {                    if(Chrarray[i] = ='0') {Chrarray[i]='1'; }                    Else if(Chrarray[i] = ='1') {Chrarray[i]='0'; }                }            }            //stitching characters into a string            foreach(CharChinchChrarray) {Result+=ch; }            returnresult; }
View Code

One of the methods, implementation is not unique, time is more daring, also did not make a certain optimization, just for the sake of familiarity with the algorithm and written.

Hope to help beginners, but also welcome you to propose changes.

The full code can be downloaded here

Https://github.com/hwqdt/Catcher.Equation

Simple application of genetic algorithm-solving equations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.