Click here to Skip to main content
Click here to Skip to main content

A Simple C# Genetic Algorithm

By , 21 Aug 2003
 

Abstract

In this article, we shall produce a simple genetic algorithm in C#. It will not be multi-threaded, nor will it contain exotic operators or convergence criteria (i.e. a condition where many of the solutions found are very similar). It will simply demonstrate a genetic algorithm in managed code, taking advantage of some of the features of the .NET runtime.

Introduction

A genetic algorithm is an optimization technique that relies on parallels with nature. It can tackle a variety of optimization techniques provided that they can be parameterized in such a way that a solution to the problem provides measure of how accurate the solution found by the algorithm is. This measure we define as fitness.

Genetic algorithms were first conceived in early 1970's (Holland, 1975). The initial idea came from observing how the evolution of biological creatures derives from their constituent DNA and chromosomes. In this sense a simple analogy can be made with a mathematical problem made up of many parameters. Each parameter can take the place of a chromosome in the mathematical analogy of a real chemical sequence.

In nature, evolution is carried out by a process of selection typified by the expression survival of the fittest. In order to select an individual, we need a population of such individuals to choose from to produce a new generation of individuals.

For any problem that we wish to solve, we need some measure of the goodness of the solution, i.e. fitness, often a χ2 (chi-squared) measure, i.e. the better the solution, the higher the fitness returned from out function. The less fit the solutions are, the less likely that they are to survive to a successive population. By employing such a technique, the algorithm can reduce the number of possible solutions that it examines.

Many problems are internally represented in binary by various genetic algorithms. Here we will only consider a decimal representation. The internal representation of a genetic algorithm does not actually matter provided the implementation is thorough (Field, 1995).

The Problem

In our example code, we supply a test function that uses sin and cos to produce the plot below:

The optimal solution for this problem is (0.5,0.5), i.e. the highest peak. We choose this example to demonstrate how a genetic algorithm is not fooled by the surrounding local maxima (i.e. the high peaks).

Test Harness

We start by declaring a new genetic algorithm:

GA ga = new GA(0.8,0.05,100,2000,2);

ga.FitnessFunction = new GAFunction(theActualFunction);

where we the arguments are the crossover rate, mutation rate, population size, number of generations, and number of parameters that we are solving for. We declare the FitnessFunction property as:

public delegate double GAFunction(double[] values);

public class GA
{
  static private GAFunction getFitness;
  public GAFunction FitnessFunction {  
    // etc.
  };
  //  etc.
}               

This then enables us to declare our fitness function the same as the delegate function:

public static double theActualFunction(double[] values) 
{
  if (values.GetLength(0) != 2)
  throw new ArgumentOutOfRangeException("should only have 2 args");
   double x = values[0];
   double y = values[1];
   double n = 9; 
   double f1 = Math.Pow(15*x*y*(1-x)*(1-y)*Math.Sin(n*Math.PI*x)
      *Math.Sin(n*Math.PI*y),2);
   return f1;
}

which is therefore accepted by the algorithm. The genetic algorithm is then set to run using:

ga.Go();

The genetic algorithm will now run for the supplied number of generations.

The Algorithm

The algorithm code contains two simple classes, GA and Genome, plus a helper class GenomeComparer.

The Genome class can be thought of as a simple container. The underlying structure is an array of doubles within the range of 0 to 1. The user is expected to take these values and scale them to whatever values they require. Since mutation occurs on the genome, the Mutate method is found in this class. The Crossover operator requires access to the private data of the Genome, so it is also a member function which takes a second Genome, and outputs two child Genome objects. The fitness of a particular genome is also stored within the Genome object. There are some additional helper functions that maybe found in the code itself.

The GA class does all the work. The genetic algorithm consists of the following basic steps:

  1. Create a new population
  2. Select two individuals from the population weighting towards the individual that represents the best solution so far.
  3. 'Breed' them to produce children.
  4. If we don't have enough children for a new population return to step 2.
  5. Replace old population with new.
  6. If we have not produced enough generations return to step 2.
  7. We have finished.

When selecting individuals to breed, we use what is called the Roulette wheel method. This is where fitter individuals have a larger proportion of the 'wheel' and are more likely to be chosen. We chose to store the finesses cumulatively in System.Collections.ArrayList as it had some nice features like sorting. Unfortunately, its binary search method was only for exact values, so we had to implement the following work around:

mid = (last - first)/2;

// ArrayList's BinarySearch is for exact values only
// so do this by hand.
while (idx == -1 && first <= last)
{
  if (randomFitness < (double)m_fitnessTable[mid])
  {
    last = mid;
  }
  else if (randomFitness > (double)m_fitnessTable[mid])
  {
    first = mid;
  }
  mid = (first + last)/2;
  // lies between i and i+1
  if ((last - first) == 1)
     idx = last;
}

The GenomeComparer class inherits from the IComparer interface. Each generation is stored in a System.Collections.ArrayList, and we wish to sort each generation in order of fitness. We therefore need to implement this interface as follows:

public sealed class GenomeComparer : IComparer
{
    public GenomeComparer()
    {
    }
    public int Compare( object x, object y)
    {
        if ( !(x is Genome) || !(y is Genome))
            throw new ArgumentException("Not of type Genome");
        if (((Genome) x).Fitness > ((Genome) y).Fitness)
            return 1;
        else if (((Genome) x).Fitness == ((Genome) y).Fitness)
            return 0;
        else
            return -1;
    }
}

Note that we need to explicitly cast the ArrayList elements back to a Genome type. We also make the class sealed as there is no point inheriting from it.

A Quick Note On Operators

We mentioned briefly, two operators, crossover and mutation, and we shall explain these in a little more detail here.

Crossover simply takes two genomes, splits them at some point and produces two new genomes by swapping the end parts, e.g.

10 20 30 40 50 60 70
80 90 00
 
10 20 30 40 50 60 70
30 20 10
   
===>
   
00 90 80 70 60 50 40
30 20 10
 
00 90 80 70 60 50 40
80 90 00

The split occurs at a randomly chosen point along the length of the genome, and the split only occurs if a probability test is passed. This is typically set quite high which reflects what happens in Nature.

Mutation, in comparison, happens rarely so the probability that it occurs is set quite low, typically less than 5%. Each gene within the genome is tested in turn to see it is allowed to mutate, and if so it is replaced with a random number, e.g.

10 20 30 40 50 60
70
80 90
      ===>      
10 20 30 40 50 60
22
80 90

Results

With our simple example we know that the optimal solution is at (0.5, 0.5), and we find after 250 generations we find a solution extremely close to this (within 4 significant figures). The progress of the GA can be seen below:

 

Conclusion and Notes.

A genetic algorithm does not provide a magic bullet solution to all minimization/maximization problems.  In many cases other algorithms are faster and more practical.  However for problems with a large parameter space and where the problem itself can be easily specified, it can be an appropriate solution. 

Whilst writing this I learnt several features of C# that I'd like to summarize here (coming from a C++ background):

  • The System.Collections.ArrayList container only does shallow copies.
  • The System.Collections.ArrayList container's binary search only works for exact values.
  • An obvious thing, but simply defining a variable, doesn't necessarily assign it a value.
  • Implementing the IComparer interface is fairly trivial (see GenomeComparer class).

Further improvements to the algorithm can be made by implementing all sorts of weird and wonderful operators. I'm sure someone will be able to tell me an easier way to supply the number of parameters the problem has automatically rather than using the GA constructor and the delegate function.

References

Field, P., "A Multary Theory for Genetic Algorithms: Unifying Binary and Non-binary Problem Representations", Ph.D. Thesis, 1995, Queen Mary and Westfield College.

Holland, J.H., "Adaption in Natural and Artificial Systems", MIT Press, 1975, (1992 Edition).

Lippman, S.B., "C# Primer, A Practical Approach", Addison-Wesley, 2002, (1st Edition).

Links

The following may be of interest:

  • Wall, M., "GALib - a C++ implementation of a genetic algorithm," MIT, 1999.
  • A Russian version of this article may be found here translated by Vladimir Lioubitelev.

History

  • 22nd August, 2003 - Update to code.
  • 3rd May, 2003 - Update to conclusion.
  • 15th Mar, 2003 - Update to article text.
  • 16th Nov, 2002 - Update to article text.
  • 6th Nov, 2002 - Initial revision.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

About the Author

Barry Lapthorn
United Kingdom United Kingdom
Member
Jack of all trades.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSmall bugmemberMember 98133805 Feb '13 - 12:01 
Hi Barry,
 
I think there may be a small bug in the binary search part of your roulette selection method. Here's the relevant code:
 
while (idx == -1 && first <= last)
            {
                if (randomFitness < m_fitnessTable[mid])
                {
                    last = mid;
                }
                else if (randomFitness > m_fitnessTable[mid])
                {
                    first = mid;
                }
                mid = (first + last)/2;
                //  lies between i and i+1
                if ((last - first) == 1)
                    idx = last;
            }
 
If I'm not mistaken,
randomFitness < m_fitnessTable[mid]
should be
randomFitness <= m_fitnessTable[mid] 
The way it stands, it's possible to skip both the "if" and "else if" statements, resulting in a potentially infinite loop.
 
Thanks for writing up this example, by the way.
Thomas
QuestionMutation biased?memberMember 84173078 Jun '12 - 10:31 
I saw that the code for mutate takes the average of the old value and a random number. Doesn't this have a high bias towards numbers in the middle (e.g. 0.5 will never mutate into 0.2 and you can only get to .9 if the old value is already >0.8)?
 
Since the final answer is smack in the middle, this does seem a bit biased.
 
On the other hand, I tested this on functions that had the optimum at 0.9; 0.9 and it found the correct solution. It failed at 0.99; 0.99. And of course, real life problems may have a high likelihood for answers near the middle. But I would at least expect some discussion on the way Mutate is implemented.
 
P.S. The article is a good kick-start into GA experiments. Nice work!
GeneralMy vote of 5memberCS140129 Jun '11 - 19:20 
hh
Generalfunction approximation using your GAmemberIntelevgen4 Jun '11 - 11:40 
Hello, Mr.Lapthorn!
I've tried to use your genetic alg. to approximate some functions just for my interest. But... it doesn't work correctly =(
Could you please help me, if you have some free time? Maybe you have tried that too?
The fitness function I used is the next:
 
public static double MHK(double[] values)
{
// f( x )= z(4) x^4+z(3)x^3+z(2)x^2+z(1)x+(z0) // approximation function
// avaiblePoint - is a list of Sin(x) function points on[-pi/2;pi/2]
 
double delta = 0;

for (int i = 0; i < avaiblePoints.Count; i++)
{
delta+= Math.Abs(avaiblePoints[i].Y - (values[4] * Math.Pow(avaiblePoints[i].X, 4) + values[3] * Math.Pow(avaiblePoints[i].X, 3) + values[2] * Math.Pow(avaiblePoints[i].X, 2) + values[1] *
avaiblePoints[i].X + values[0] ));
}
return delta;
}
 
My contacts: icq 3693100, e-main intelevgen@gmail.com
 
Best regards, Eugene
GeneralUrgent needmemberkindkirthi24 Feb '11 - 4:57 
please help me i am doing project based on Genetic algorithm.it can be applied in text it can be summarized the text by using GA please help me it is urgent if any one having coding send
Generalgenetic algorithmmembersourabh maheshwari20 Jan '11 - 22:03 
hello...
i am having a project on "CENTRALIZED COLLEGE ALLOTMENT" and it is to be done using genetic algorithm in c sharp....
can anyone help me out finding the code for it or can anyone just give a brief idea about it.....
its urgent...
Thank you...
Generali was looking for a GAmembermattica30 Sep '10 - 4:52 
I was looking for a Genetic Algorithm written in C#, but this is not a GA.
 
The mutation works, but crossover is a total lark. For GAs to work on real problems, you need to invoke a true stochastic process combined with implicit parallelism. This is acheived by reducing the genome to a bit string, which is not done here. To perform a proper real-valued GA there is some good results with interpolating in the crossover, but this is better known as Differential Evolution.
GeneralRe: i was looking for a GAprotectorBarry Lapthorn1 Oct '10 - 5:31 
I'm not entirely sure what your point is. If you think that genomes should have a binary representation, then I really suggest that you read: Field, P. (1995): A Multary Theory for Genetic Algorithms: Unifying Binary and Nonbinary Problem Representations [^]
Regards,
 
Barry

GeneralRe: i was looking for a GAmembermattica1 Oct '10 - 11:39 
I did not say that a GA must have a binary encoding but without reducing each of the variables to some smaller building-blocks (as is the case with binary encoding or even the multary encoding in the suggested dissertation), your GA will not work effectively.
 
You give an example of a two-variable problem, max f(x, y).
Since crossover only happens between x and y then you will only be able to create solutions that have any of the random values of x and y created in the initial population. You are completely relying on mutation to move from the initial populations values. You might as well systematically check every x in the initial population with every y and return the pair with the highest value.
 
As I stated, you may forego the low-level building block approach but you would need to introduce interpolation and extrapolation crossover operators ala differential evolution.
 
I realize this may sound like some rant with a misdirected or ulterior motive. My reason is simply that this is the first page that google offers for a search for [genetic algorithm C#]. I am concerned people are trying this on harder problems and not getting satisfactory results.
GeneralRe: i was looking for a GAmembermarschills22 Nov '10 - 2:04 
The title of the article does say a simple c# genetic algorithm, I don't think it's offering itself as a huge framework. And I doubt people who are using genetic algorithms in business will rely solely on this to plug their values into.
 
To Barry: I've written a .NET 3.5 version of the article's code here, I hope you don't mind. I'm also in the middle of doing my own version with a bit strings, as a learning experience more than anything.
GeneralRe: i was looking for a GAprotectorBarry Lapthorn22 Nov '10 - 6:24 
I hope you find it helpful. The title does say "Simple" after all Smile | :)
Regards,
 
Barry

GeneralGenetic Algorithmmemberarun114830 Sep '10 - 3:06 
Im doing project in job scheduling. i need source code for genetic algorithm using java. can anyone help me...... Smile | :)
GeneralHellomemberJoannecw861 Jul '10 - 23:46 
Hello there,
do you have any Genetic Algorithms in C code using integer representation? I would like to learn it. thanks Smile | :)
Questionto change interval(define area)memberqzpas200827 Apr '10 - 3:24 
Hello Barry!!
My name is Max!
I'm reading Your article!
A Simple C# Genetic Algorithm[^]
So, it's very nice, and helpfull for me.
But i have a Question for You.
Where in the code, i need to change interval(define area) for my function
Math.Pow(Math.Cos(x) + Math.Sin(y / 2.0), 6.0);
 
my email: mr.maximus86@gmail.com
Thanks!!
GeneralPatient scheduling using Genetic algorithmmembersetare_yousefi25 Mar '10 - 9:05 
I am Ph.D student and for my project I need the source code of patient scheduling using Genetic algorithm in C#.
Is there anyone here that can help me,plzzzzz I need it.
Thanks
Questiongenetic algorithmmembermanimekalai198816 Feb '10 - 17:59 
i am going to do a project on genetic algorithm for job optimization....if you have a code please send to me..
its urgent...
my mailid is kalaianu1988@gmail.com
 

 
with regards,
Manimekalai
Generalcode to use BULLETS AND NUMBERING dialog box of MS WORD in c# applicationmembersantosh_anu6 Oct '09 - 0:42 
is there any way to include BULLETS AND NUMBERING DIALOG BOX in C# Application
Questionnumber range?memberJernej200921 Jun '09 - 23:31 
Hello,
 
first thanks,
 
where in program to change interval of searching maximum(it was [0..1.0] for example to [-1.0,1.0]
QuestionHow to change optimal (0.5,0.5)membersport_life5 Apr '09 - 17:45 
Please show me where you put number optimal?
GeneralNeed Help On Genetic algorithmmemberdontyoudare12325 Mar '09 - 2:48 
I am working on image compression using genetic algorithm. For image decompression i need to use genetic algorithm, Can anyone please help me on this. Its urgent
Generalsource code for exam scheduling with GA in VB.netmemberAWEDA OMOTOYOSI MOROLAYO19 Dec '08 - 2:32 
pls could you send me a source code to schedule university exams using genetic algorithm. I wud really appreciate it cos it is urgent. ur code is nice by the way. thanks
GeneralRe: source code for exam scheduling with GA in VB.netmemberahyeek17 Feb '09 - 16:15 
you can acquire a .NET C# GA sample code from here: www.geneticalgorithm.ahyeek.com
 
There are several package available, choose the one suitable for you.
Hope this help.
 
Ahyeek
 
Since 1998 ...

GeneralThank you!memberAsmor25 Nov '08 - 9:30 
I'm doing a senior honors project involving genetic algorithms, so this is going to help me a lot.
 
Thanks!
GeneralOPtymalizationmembermakdelete20 Oct '08 - 4:46 
Is this code work in visual c#? haw I can run this code in visual? Have You got any working code (optymalization any mathematic function) in Visual C#? pleas help me it's very importent to me Smile | :)
GeneralRe: OPtymalizationmemberahyeek17 Feb '09 - 16:16 
Take a look at: http://www.geneticalgorithm.ahyeek.com/detail.php?c=5[^]
 
GA sample application provided with fitness value graph visualization imposed.
 
Ahyeek
 
Since 1998 ...

GeneralGenetic Algorithm (GA) In Solving Vehicle Routing Problem In .NET C# Codememberahyeek5 Aug '08 - 21:44 
About Genetic Algorithm programming, you can refer to here for program code implemented in C# as well.
Same concepts, the simulationis developed purposely for learning purpose with all genetic algorithm parameters in show for exam. Several moving graph showing the analysis for further understanding.
 
There are a lots of other useful an interesting features implemented in the simulator and the author think it will be too much to state here. So, let download the system and try it! You will discover more.....
 

Genetic Algorithm (GA) Simulation Solving Vehicle Routing Problem (Shortest Path Finding) Implemented in .NET C#

 
Since 1998 ...

GeneralIMPORTENT: Please help me for Senoir Project on 14 JUN, 2008memberSalmaAlnajim7 Jan '08 - 8:29 
Cry | :(( Please can I ask you questions?
How I can output a 3D-graph in the output window according to Fitness functions in Genetic Algorithm? Can you please help me with C# language?? And where can I do the window interface? in which program, program.cs or others? and where to put my fitness functions and input data to it_let the user to input float/double numbers to the program to run the fitness functions to evaluate the optimal solutions?
 
Regards,
Salma Alnajim
GeneralGood codesmemberdiegoeddy5 Sep '07 - 3:54 
Your codes are excellent.
 
Eddy
Questiongenetic algorithmmemberjenif18 Jan '07 - 0:21 
Hai
Is it possible to have genetic algorithm with gaussian mutation. If so would you please send me the coding of genetic algorithm with gaussian distribution.. also i need c# coding to find the convergence time for genetic algorithm.
 
Otherwise send me the coding og evolutionary programming with gaussian mutation..
 
Its very urgent..
Reply soon please.
my mail id: jeni_vlsi@yahoo.co.in
with regards
Jenifer
GeneralsatisfiedmemberBallitano27 Nov '06 - 10:51 
I like this article very mucthBig Grin | :-D
Generalmachine cell formation using genetic algorithmmembersinbear3 Sep '06 - 19:39 
hi, experts, my project on solving the machine cell formation problem using genetic algorithm has encounter problems, the requirment for this project is to arrange the machines into different cells that can get the optimize timing and most efficiency, i don't know how to use the C++ to solve this problem, can anyone give me a hand!!!, this is my FYP, if i can't do it, i can't graduate, so any suggestion or need more detail about this project please contact me at sinbearzc@Hotmail.com, thank you so much!!!
GeneralThanks!memberjwhooper25 Mar '06 - 15:25 
As an introduction to C#, I attempted to write a genetic algorithm for the Eight Queens chess problem. It just wouldn't work.
 
My solution was to Google to here, adapt my project to use your tested GA DLL, and viola! Our implementations weren't so different, except for one minor thing -- yours works.
 
Sometimes it's good to struggle, but after that it is even better to see some good code that works, so thank you very much.
 
I'm still trying to figure out parts of it. Neat stuff.
 


GeneralRe: Thanks!protectorBarry Lapthorn3 Jun '06 - 14:00 
No problem, glad it helped!

 
Regards,
 
Barry

Question&quot;survival of the fittest&quot;?membercplas19 Dec '05 - 15:39 
>In nature, evolution is carried out by a process of
>selection typified by the expression survival of
>the fittest.....The less fit the solutions are,
>the less likely that they are to survive to a
>successive population.
 
On a side note, to the less informed, "Survival of the Fittest" is a tautology as "Fittest" is defined as those who survive. Therefore, this can be restated as “Survival of those that survive”, a meaningless statement. Google it.

AnswerRe: &quot;survival of the fittest&quot;?memberNatLang1 Mar '06 - 8:27 
This kind of word play is the only thing meaningless here. "Survival of the fittest" does have a specific meaning because survival does NOT always imply that the survivor was the fittest individual for a given environment.
 
Go to any hospital to see many examples of this. Two people might injest the same amount of some poison, but one will die because he is not near a hospital. Proximity to a hospital has nothing to do with the "fitness" of an individual to survive the poisoning. Were the roles swapped, the other person would have survived.
 
In fact, the tautology you imagine is caused by your own misinterpretation of the definition of "fittest". It is not defined (biologically) as those who merely survive, but by those who have ADAPTED to survive in a given situation. Therefore, "survival of the fittest" means that those who have adapted to an environment will be more likely to survive than those who would depend on some external influence to make the environment more hospitable. It is a small difference, yes, but an important one.
 

 
That will be $0.02 please. Cash or charge?
GeneralC sharp 2.0 versionmemberYtoba30 Aug '04 - 15:42 
Smile | :) Hi Barry !
 
I modified the code to use c sharp 2.0 new features.
 
If you were interested, do you have an email @ so I can send you the result of my modifications.
 

 
Ytoba
GeneralRe: C sharp 2.0 versionmemberangelodiego21 Jun '06 - 22:57 
Hi Ytoba,
I'm interested in the v. 2 code to see how you improved it with the new framework, is it possible to have it?
Thanks, Diego
GeneralRe: C sharp 2.0 versionprotectorBarry Lapthorn22 Jun '06 - 8:24 
You want this article http://www.codeproject.com/cs/algorithms/simplegenalg.asp[^]
 
Regards,
 
Barry

Questionhelioseismologist ??membermliss21 Jun '04 - 5:04 
Anybody know what this is?
 
Mike
AnswerRe: helioseismologist ??protectorBarry Lapthorn22 Jun '04 - 9:41 
Someone who studies solar oscillations in order to determine what physical processes are occuring inside. Just a guess Wink | ;)

 
Regards,
 
Barry

GeneralGA Bugmemberbliggy19 Apr '04 - 23:47 
Hi all, I found that in the CreateNextGeneration() function there was a small problem with the elitism functionality. In the statement seen below it only makes a shallow copy (as Barry mentioned in the article) of the genome._genes member array:
 
if (_elitism)
g = (Genome)_thisGeneration[_populationSize - 1];

 
then as the function progresses and applies mutations to random genomes of the current generation, it actually can end up mutating the best genome from the current generation and you therefore lose your best solution when the mutated g is put into the next generation. I noticed that my solutions were approaching a limit of about 3% error when this was the case - essentially it could be described as partial elitism I guess. Anyhow, when I fixed this, the error in my solutions was reduced by at least 3 orders of magnitude.
 
Cheers,
Dave
GeneralRe: GA BugeditorBarry Lapthorn20 Apr '04 - 9:04 
Dave,
 
Thanks for that - I'm not actively maintaining the code, but I'll incorporate your fix when I get a chance. It was my first C# program, so you'll have to excuse any errors that I might have made!!! Doubtless there are a few more.
 
Glad to see that you've looked through the code though! Smile | :)
 

 
Regards,
 
Barry

GeneralRe: GA Bugmemberbliggy22 Apr '04 - 3:34 
I am just glad that someone out there wrote a C# GA program so that I didn't have to Big Grin | :-D and I am sure that it will be helpful to many others like me!
 
Cheers,
Dave
GeneralFinding the minimumsussAnonymous7 Apr '04 - 2:15 
How would you go about finding the minimum. For example how would you alter the Roulette selection to select for minimum.
GeneralRe: Finding the minimumeditorBarry Lapthorn7 Apr '04 - 2:19 
The minimum is just the reciprocal of the maximum, and vice versa, i.e. if your minimum function f(x1, x2, x3....xN), use a function that is g(x1, x2, x3...xN) = 1 / f(x1, x2, x3...xN) etc.
 
You don't need to change the Roulette Wheel selection.
 
Regards,
 
Barry

GeneralRe: Finding the minimummemberJernej200921 Jun '09 - 23:25 
The easiest way is to multiplay function by -1
GeneralGear Ratio ProblemsussAnonymous11 Mar '04 - 2:52 
i have a simple gear ratio problem to solve. Just been looking at your GA program which is really good. Would it be possible thou to change it so it could solve an equation with 4 variables instead of two?
GeneralRe: Gear Ratio ProblemsussAnonymous12 Mar '04 - 2:36 
i have now done this but also have another problem i need to constrain the 4 variables to a range of 12 to 60 any ideas on this?Unsure | :~
GeneralRe: Gear Ratio ProblemeditorBarry Lapthorn16 Mar '04 - 9:01 
It should just be a simple scaling problem, i.e.
 
public static double theActualFunction(double[] values)
{
 if (values.GetLength(0) != 2)
  throw new ArgumentOutOfRangeException("should only have 2 args");
 
  double x = (values[0] * 48.) + 12.;
  double y = (values[1] * 48.) + 12.;
  // or use a loop for multiple values, and consider
  // putting the scaling function in its own function
  // to avoid repetition.
  // then use x & y etc.
}
 
The 'values' are always between 0 and 1, so you just need some simple transform to get them to the values you want.
 
Regards,
 
Barry

GeneralRe: Gear Ratio ProblemsussAnonymous18 Mar '04 - 2:47 
yeah i was think about doing it that way.
Many Thanks Smile | :) JIM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 22 Aug 2003
Article Copyright 2002 by Barry Lapthorn
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid