# Fitness function in genetic algorithm based on an interval

I am writing an app, where when a ball is shot from a canon it is supposed to land in a hole that is on a given distance. The ball is supposed to land between the distance of the beginning of the hole and the end of the hole. The size of the hole is 4m and the size of the ball is 0.4m. My problem is that I am not sure how to write the fitness function for this. The place where the ball falls should be close to this interval of [D, D+3.6], where D is the distance of the hole. If anyone could give me a hint on how to approach this problem, I would be grateful.

• Have you definitely been asked to solve using a GA? This would be OK for a toy/learning example, but at this level of complexity is far easier to solve analytically that applying a GA. – Neil Slater Oct 24 '18 at 11:39
• yes, I must do it using GA – ivaa14 Oct 24 '18 at 12:09

Genetic algorithms work best when given a scalar fitness value that increases smoothly, so that you can compare two population members regardless of whether they failed or succeeded at the task.

That usually requires you to analyse the problem, and come up with a measure that would improve as an individual gets closer to solving a task. It generally helps if you score better for an individual if they solve a problem "better". You want to avoid simple boolean success/fail metrics.

A simple measure of how well an individual has done is to use the absolute distance it was away from a "perfect" shot (where the middle of the ball hits the middle of the hole). The only issue with this is that a perfect shot scores 0, whilst a miss scores 2+, and you want the best result to have the highest fitness. This can be fixed simply, take the negative of the absolute distance:

$$F = -|D_{hole} - D_{ball}|$$

where $$D_{hole}$$ - and $$D_{ball}$$ are horizontal distances from origin to centre of each object.

There is no requirement for fitness score to be positive. This will score $$F \lt -2$$ for a miss, $$-2 \lt F \lt 0$$ for hit, and $$0$$ for a perfect shot.

For GAs you don't have to care as much about differentiability or gradient of the fitness function, provided it gives reasonably good ranks between quality of individuals. So there is no point using e.g. a squared error metric here, although you could if you wished.