Binary Encoding and Gray Codes

How a genetic algorithm maps real-valued variables to bit strings and back. Precision and string length, decoding with worked examples, concatenating several variables, Hamming cliffs, the reflected Gray code and its conversion formulas, what Caruana and Schaffer and Whitley found about Gray coding, a 30-seed comparison on De Jong's sphere and Rosenbrock functions, and real-valued representation as the alternative.

A genetic algorithm encodes a real variable on $[L, U]$ with $n$ bits by the linear map $x = L + k\varepsilon$, with step $\varepsilon = (U - L)/(2^n - 1)$, so a precision $\varepsilon$ needs $n = \lceil \log_2((U - L)/\varepsilon + 1) \rceil$ bits: 11 for 0.01 on De Jong's $[-5.12, 5.12]$. Under standard binary, adjacent integers can differ in every bit, as 127 and 128 do on 8 bits. The reflected Gray code, $g = k \oplus \lfloor k/2 \rfloor$, puts every pair of grid neighbors one flip apart, so it never adds local minima under one-bit moves. On Rosenbrock's F2 at 8 bits per variable it has 61 against 226 for binary (103 on the grid). In 30 seeded runs, Gray coding helped on Rosenbrock's function ($A$ from 0.55 to 0.73) and was no better on the sphere ($A$ from 0.10 to 0.45); no code wins on every function.

In Goldberg's $x^2$ example the string 01101 simply meant the integer 13. Real problems are rarely so obliging. De Jong's sphere function asks for three coordinates, each a real number between $-5.12$ and $5.12$, and the minimum sits at zero. Under the usual code, the two 8-bit strings closest to zero differ in all eight bits. This article sets out how a real number is written as bits, and shows that the choice of code can decide whether a search finds the minimum: in a small example below, a search by single bit flips reaches the minimum from all 32 starting strings under one code and from only 17 under the other.

Before a simple genetic algorithm can search a space of real numbers, each real variable has to be mapped to a block of bits. That mapping is the encoding. It decides three things:

  • which candidates are reachable at all;
  • how finely the space is sampled;
  • which candidates a single mutation can reach from a given one.

First we set out the standard linear mapping, its precision, and how to choose the number of bits. Then we join several variables into one string. Next we meet the Hamming cliffs that the standard code creates, and the reflected Gray code that removes them. Finally we see what the literature and a 30-seed experiment on De Jong's functions found, and look at the alternative of not encoding real numbers in bits at all. The article assumes the simple genetic algorithm.

Mapping an interval to bit strings

Let a variable $x$ lie in an interval $[L, U]$, and give it $n$ bits. An $n$-bit string $b_1 b_2 \dots b_n$, read with the most significant bit first, is an integer

$$k = \sum_{i=1}^{n} b_i \, 2^{\,n-i}, \qquad 0 \le k \le 2^n - 1.$$

The standard linear decoding sends $k = 0$ (all zeros) to $L$ and $k = 2^n - 1$ (all ones) to $U$, with equally spaced points between:

$$x = L + k \, \varepsilon, \qquad \varepsilon = \frac{U - L}{2^n - 1}.$$

The step $\varepsilon$ is the precision of the encoding: the distance between neighboring representable values. A real value that falls between grid points is represented by the nearest one, so the representation error is at most $\varepsilon / 2$.

Three worked examples, each computed and checked:

  • Precision from length. For $1 \le x \le 16$ with $n = 6$ bits, $\varepsilon = 15 / 63 = 0.238$ to three places. Truncating this to 0.23 understates the step.
  • Precision for an 8-bit variable. For $20.1 \le x \le 45.6$ with $n = 8$, $\varepsilon = 25.5 / 255 = 0.1$ exactly. So the 256 representable values are 20.1, 20.2, and so on up to 45.6.
  • Decoding and encoding. For $2 \le x \le 17$ with $n = 4$, $\varepsilon = 15 / 15 = 1$. The string 1010 is $k = 8 + 2 = 10$, which decodes to $x = 2 + 10 \times 1 = 12$. Going the other way, $x = 12$ gives $k = (12 - 2) / 1 = 10$, whose binary form is 1010. A common slip writes 1100, which is 12, the value of $x$ rather than of $k$.

Choosing the length. The formula for $\varepsilon$ runs backward too. To guarantee a precision of at most $\varepsilon$, the number of bits must satisfy $(U - L)/(2^n - 1) \le \varepsilon$, so

$$n = \left\lceil \log_2\!\left(\frac{U - L}{\varepsilon} + 1\right) \right\rceil.$$

Example (ten bits on De Jong's interval). Ten bits are just short of a precision of 0.01 on De Jong's interval $[-5.12, 5.12]$, which has width 10.24. They give $10.24 / 1023 = 0.01001$, a hair over the target. The formula asks for $\lceil \log_2 (10.24 / 0.01 + 1) \rceil = \lceil \log_2 1025 \rceil = 11$ bits, since $2^{10} = 1024 < 1025$. A precision of 0.001 needs $\lceil \log_2 10241 \rceil = 14$ bits, since $2^{13} = 8192 < 10241 \le 2^{14} = 16384$.

Some authors divide by $2^n$ instead of $2^n - 1$. Then 10 bits on $[-5.12, 5.12]$ give a step of exactly 0.01, and the upper bound itself is not representable. De Jong (1975) discretized his test functions with a power of two of points on each axis, for example 1,024 points on $[-5.12, 5.12]$ at a nominal resolution of 0.01, as described in a binary GA on De Jong's test functions. The two conventions differ only in whether $U$ is on the grid.

When a variable takes a fixed set of values whose count is not a power of two, some bit patterns are left over. Whitley (1994) gives the example of a variable with exactly 1,200 values. It needs 11 bits, and $2^{11} - 1200 = 848$ of the patterns represent nothing. They must be given no evaluation or a worst-possible one, or mapped to legal values so that some values are represented twice. Whitley treats the choice as part of designing the evaluation function.

The sphere function has three variables, not one, so several blocks have to share a string.

Several variables

A candidate with several variables is encoded by concatenating their blocks. The course's second assignment, examined in a binary GA on De Jong's test functions, encoded De Jong's three-variable sphere function F1 with 8 bits per variable, a 24-bit string. On $[-5.12, 5.12]$ with 8 bits, $\varepsilon = 10.24 / 255 = 0.040157$. The string

10000010 10000011 01111101

splits into $k = 130, 131, 125$. These decode to $x \approx (0.1004, 0.1405, -0.1004)$, with $\sum x_i^2 = 0.0399$. That was the best 8-bit solution the submitted report gave for F1.

Concatenation has a consequence for crossover. One-point crossover cuts the string at a single position. So blocks that sit next to each other on the string are more likely to be inherited together than blocks at opposite ends. Whether that matters depends on whether the variables interact. The schema theorem article measures the effect of position through a pattern's defining length, the distance between its outermost fixed bits.

Crossover moves whole blocks; mutation changes single bits inside them. The next section shows what a single flip does to the number a block encodes.

Hamming cliffs

Bit-flip mutation at the usual low rates changes one bit or none in most offspring. So the candidates a mutation reaches most easily are those at Hamming distance 1, differing in a single bit. Under standard binary coding, Hamming distance and numerical distance can disagree badly.

Example (the two grid points beside zero). On the 8-bit grid of $[-5.12, 5.12]$, the two grid points closest to zero are $k = 127$ and $k = 128$, and all eight bits must flip to move from one to the other. Adjacent integers can differ in every bit:

$k$ Binary $x$ on the 8-bit grid of $[-5.12, 5.12]$
127 01111111 $-0.020078$
128 10000000 $+0.020078$

The two grid points closest to zero, where the sphere function has its minimum, are as far apart as two 8-bit strings can be. Caruana and Schaffer (1988) called such a gap a Hamming cliff.

Cliffs are not rare. Over all 255 pairs of adjacent integers on an 8-bit grid:

  • 128 pairs differ in one bit;
  • 64 differ in two;
  • 32 differ in three, and so on, halving each time;
  • the single pair 127 and 128 differs in all eight.

The converse also holds: a single bit flip can move a long way. Flipping the leading bit of any string moves $k$ by 128, half the range.

The counts follow from how binary addition carries, and the pattern is easier to see on 5 bits. Adding 1 to $k$ flips the trailing run of ones to zeros and the 0 before it to a 1. So the number of bits that change is one more than the number of trailing ones in $k$. Half of all integers end in 0 and change one bit, and a quarter end in 01 and change two. The pattern continues up to $k = 15$ (01111), whose successor 16 (10000) differs in all five. On 8 bits the same count gives the list above. Among $k = 0, \dots, 254$, exactly $2^{8-j}$ values end in a 0 followed by $j - 1$ ones, and their successors differ from them in $j$ bits: 128 for $j = 1$, 64 for $j = 2$, down to 1 for $j = 8$. These add up to all 255 pairs.

How many bits differ between the codes of k and k + 1 on a 5-bit grid. Under standard binary (bars) the count follows a ruler pattern; notice the cliffs of four bits at 7 to 8 and 23 to 24 and of five bits at 15 to 16. Under the reflected Gray code (dashed line) every step is a single bit.
How many bits differ between the codes of $k$ and $k + 1$ on a 5-bit grid. Under standard binary (bars) the count follows a ruler pattern; notice the cliffs of four bits at 7 to 8 and 23 to 24 and of five bits at 15 to 16. Under the reflected Gray code (dashed line) every step is a single bit.

The dashed line in the figure is flat. The code that achieves that is the subject of the next section.

The reflected Gray code

A Gray code orders the bit strings so that consecutive integers always differ in exactly one bit. The usual one is the binary reflected Gray code. It takes its name from its construction: the $n$-bit list is the $(n-1)$-bit list with a 0 prefixed, followed by the same list in reverse order with a 1 prefixed. Frank Gray patented it for pulse code communication (Gray, 1953). For three bits:

$k$ 0 1 2 3 4 5 6 7
Binary 000 001 010 011 100 101 110 111
Gray 000 001 011 010 110 111 101 100

The construction can be carried out by hand. Start from the 1-bit list 0, 1. Prefix it with 0, then append the list in reverse order prefixed with 1:

Step List
1 bit 0, 1
2 bits: 0 + (0, 1), then 1 + (1, 0) 00, 01, 11, 10
3 bits: 0 + (00, 01, 11, 10), then 1 + (10, 11, 01, 00) 000, 001, 011, 010, 110, 111, 101, 100

Why does every step change exactly one bit? Here is the argument by induction on $n$. For $n = 1$ the list is 0, 1, and its two entries differ in one bit. Suppose consecutive entries of the $(n-1)$-bit list differ in one bit. Each half of the $n$-bit list is that list, forward or reversed, with a common prefix, so consecutive entries within a half differ in one bit. At the join, the last entry of the first half and the first entry of the second half are the same $(n-1)$-bit string, with prefixes 0 and 1. So they too differ in one bit. The code is also cyclic. The first entry of the $n$-bit list is the first $(n-1)$-bit entry prefixed with 0, and the last is the same entry prefixed with 1, because the second half is reversed. For three bits these are 000 and 100.

Conversion. Listing the code is fine for 3 bits but not for 16. A formula converts directly. From binary $b_1 \dots b_n$ to Gray $g_1 \dots g_n$, keep the first bit and XOR each later bit with the one before it:

$$g_1 = b_1, \qquad g_i = b_{i-1} \oplus b_i \quad (i = 2, \dots, n).$$

As an operation on integers, $g = k \oplus \lfloor k / 2 \rfloor$, that is, k ^ (k >> 1). The inverse accumulates XORs from the left:

$$b_1 = g_1, \qquad b_i = b_{i-1} \oplus g_i, \quad \text{so} \quad b_i = g_1 \oplus g_2 \oplus \dots \oplus g_i.$$

The inverse follows from the forward rule: XORing both sides of $g_i = b_{i-1} \oplus b_i$ with $b_{i-1}$ gives $b_{i-1} \oplus g_i = b_i$, and applying this from $i = 2$ upward builds the running XOR.

Why the formula gives the reflected list. The proof is by induction on $n$, following the construction. For $n = 1$ the formula gives $g_1 = b_1$, the list 0, 1. Suppose the formula gives the $(n-1)$-bit list, and take an $n$-bit integer $k$.

  • If $k < 2^{n-1}$, its leading bit is $b_1 = 0$. Then $g_1 = 0$ and $g_2 = 0 \oplus b_2 = b_2$, and the remaining bits follow the rule on $b_2 \dots b_n$. So the code of $k$ is 0 followed by the $(n-1)$-bit code of $k$, which is entry $k$ of the first half.
  • If $k \ge 2^{n-1}$, put $k' = 2^n - 1 - k$, so $0 \le k' < 2^{n-1}$. The second half lists the $(n-1)$-bit code in reverse, so its entry at position $k$ is 1 followed by the $(n-1)$-bit code of $k'$. Subtracting from $2^n - 1$, the all-ones string, complements every bit, so the binary string of $k$ is the complement of that of $k'$. Complementing both of two bits leaves their XOR unchanged, so $g_i(k) = g_i(k')$ for $i \ge 2$, while $g_1(k) = b_1 = 1$. Since $k'$ has leading bit 0, the bits $g_2(k') \dots g_n(k')$ are its $(n-1)$-bit code, by the first case. So the formula gives 1 followed by the $(n-1)$-bit code of $k'$, as the construction requires.

The script confirms that the formula and the construction give the same list for every $n$ from 1 to 12.

For example, $k = 10$ is 1010 in binary, and its Gray code is $1,\ 1 \oplus 0,\ 0 \oplus 1,\ 1 \oplus 0 = 1111$. Decoding 1111 gives $b = 1,\ 1 \oplus 1,\ 0 \oplus 1,\ 1 \oplus 1 = 1010$, back to 10. Here is a 5-bit example, Goldberg's $k = 13$ (binary 01101), traced one position at a time in both directions:

$i$ $b_i$ Encode: $g_i = b_{i-1} \oplus b_i$ Decode: $b_i = g_1 \oplus \dots \oplus g_i$
1 0 $g_1 = b_1 = 0$ $0$
2 1 $0 \oplus 1 = 1$ $0 \oplus 1 = 1$
3 1 $1 \oplus 1 = 0$ $1 \oplus 0 = 1$
4 0 $1 \oplus 0 = 1$ $1 \oplus 1 = 0$
5 1 $0 \oplus 1 = 1$ $0 \oplus 1 = 1$

So 13 has the Gray code 01011. Decoding keeps a running XOR of the Gray bits: each row's decode value is the previous row's value XOR $g_i$, and the column recovers 01101. The rule has a simple reading. After the first bit, which is copied, a Gray bit is 1 exactly where the binary string changes value from the position before. In a GA, Gray coding changes only the step from bits to the integer $k$. The strings, the operators and the linear map from $k$ to $x$ stay the same.

What Gray coding fixes, and what it does not. The cliff at the origin disappears: 127 and 128 have the Gray codes 01000000 and 11000000, one bit apart. What Gray coding does not do is make every one-bit move a small one. The eight integers one flip away from 127 are 126 and 128, its two grid neighbors, but also 0, 64, 96, 112, 120 and 124. Under binary they are 63, 95, 111, 119, 123, 125, 126 and 255. Both codes give each string $n$ neighbors spread over the whole range. Gray coding guarantees only that the two grid neighbors are among them.

Every move a single bit flip can make on 5 bits. Each column shows the five integers reachable from string k. Squares mark moves to k - 1 or k + 1. Under binary (a) only 32 of the 160 moves are to a grid neighbor; notice that 15 and 16, the pair across the largest cliff, cannot reach each other. Under Gray (b) all 62 neighbor moves are present, on the two diagonals beside the main one, while the other moves still jump across the range.
Every move a single bit flip can make on 5 bits. Each column shows the five integers reachable from string $k$. Squares mark moves to $k - 1$ or $k + 1$. Under binary (a) only 32 of the 160 moves are to a grid neighbor; notice that 15 and 16, the pair across the largest cliff, cannot reach each other. Under Gray (b) all 62 neighbor moves are present, on the two diagonals beside the main one, while the other moves still jump across the range.

A cliff is a curiosity until it stops a search, and the next example shows that it can.

A small example shows what a cliff does to a search that moves by single bit flips. Minimize $f(k) = (k - 15)^2$ over the 5-bit integers $0, \dots, 31$. On the grid the function has one minimum, $k = 15$, and falls steadily toward it from both sides.

Example (16 is a local minimum under binary). A search that moves by single improving flips cannot get from 16 to 15 under standard binary. There 16 is 10000, and its five one-flip neighbors are 0, 17, 18, 20 and 24. The neighbors have $f$ values 225, 4, 9, 25 and 81, all worse than $f(16) = 1$. So 16 is a local minimum under binary coding: no single bit flip improves it, although it sits next to the global minimum on the grid. Under Gray coding, 16 is 11000 and 15 is 01000, one flip apart, and 16 is not a local minimum.

Steepest descent makes the difference concrete, in the sense of hill climbing. Starting from a string, move to the best of its five one-flip neighbors as long as that neighbor is strictly better, and stop otherwise. When two neighbors tie for best, take the one reached by flipping the lower-order bit. Run from each of the 32 starting strings:

Coding Strict local minima Starts ending at 15 Starts ending at 16
Standard binary 15, 16 17 15
Reflected Gray 15 32 0

Under binary, nearly half of the starts end on the wrong side of the cliff, including every start from 16 to 27. From 24 (11000), for instance, the best flip clears the second bit and lands on 16 (10000), where the search stops. Under Gray coding every start reaches 15. From 24 (Gray 10100) the path is 24, 23, 16, 15, each step a single flip. From 24, the neighbors 23 and 7 tie at $f = 64$; breaking the tie the other way gives 24, 7, 8, 15, which also ends at 15. The counts in the table hold under either rule. Which starts end at 16 under binary depends on the rule: 0 to 2 and 16 to 27 with ties to the lower-order bit, and 0 to 3 and 16 to 26 with ties to the higher-order bit.

A genetic algorithm is not a steepest-descent search. But at low mutation rates its offspring are mostly one or two flips from their parents. The same trap applies to it whenever crossover cannot supply the missing bits.

The general rule. The example is one case of a general rule, which follows from Gray coding's guarantee that both grid neighbors are one flip away. Take a point that is a local minimum under one-bit-flip moves in the Gray-coded space, so that every one-flip neighbor has a higher value. Changing one variable's $k$ by $\pm 1$ changes one bit of that variable's block and nothing else. So the point's grid neighbors ($k \pm 1$ in each variable) are among its Gray neighbors, all of them have a higher value, and the point is also a local minimum on the grid itself. Gray coding can therefore add no local minima beyond those of the grid; it can only remove some. Standard binary offers no such guarantee. On Rosenbrock's function F2 with 8 bits per variable, a grid of 65,536 points, the counts of strict local minima are:

Neighborhood Local minima
Grid neighbors, $k \pm 1$ in each variable 103
One bit flip, standard binary 226
One bit flip, Gray 61

Binary coding more than doubles the number of local minima of the grid; Gray coding removes about 40 percent of them. Each count belongs to a different fitness landscape over the same points, because the neighborhood is part of the landscape.

Fewer local minima on one function is suggestive, but it does not show that Gray coding wins in general. The literature and the experiment below both qualify it.

What the literature found

Caruana and Schaffer (1988) compared Gray and binary coding in genetic algorithms on function optimization problems and reported that Gray coding was generally better. They attributed the difference to Hamming cliffs, which make some moves between neighboring values hard under binary coding. They presented the cliff as one example of a hidden bias that arises from the interaction between a representation and the operators that search it.

Example (no code is better on average over all functions). Neither Gray nor binary coding can be better than the other on average over all possible functions. Both are one-to-one relabelings of the same set of strings. By the No Free Lunch theorems, any two such relabelings must perform the same when averaged over all functions. Any advantage on some functions is paid for on others.

Whitley (1999) made the trade-off precise in three steps:

  1. He defined a special class of functions that have the maximum possible number of local optima.
  2. He proved that the reflected Gray code induces more optima than binary over that class.
  3. He concluded, from the No Free Lunch principle, that Gray coding induces fewer optima over all the remaining functions.

Whitley's argument is that functions of limited complexity, with fewer than the maximum possible number of optima, are the ones worth optimizing. Over them Gray coding has the advantage on average. The result counts local optima under one-bit moves, so it speaks most directly to search by mutation and local moves. It does not promise that Gray coding wins on any particular function. Our own experiment shows why that caveat matters.

An experiment on De Jong's F1 and F2

The course's second assignment ran a binary GA on De Jong's functions, each configuration once. The script tools/experiments/evolution/gray_coding.py in the site repository repeats its GA with standard binary and Gray coding, with seeds 0 to 29. The settings are:

  • Functions: F1, the sphere, three variables on $[-5.12, 5.12]$; and F2, Rosenbrock's function, two variables on $[-2.048, 2.048]$; each with 8 and 16 bits per variable.
  • The GA: the assignment's own. Population 20, roulette-wheel selection on $1/(1 + f)$, two-point crossover with probability 0.9, bit-flip mutation at $1/L$, and generational replacement without elitism. The best value ever evaluated is reported.

Only the step from bits to integers differs between the two codings. So the binary runs at the assignment's budget repeat the 30-seed runs in a binary GA on De Jong's test functions exactly. The tables give the median best value found, with the interquartile range. They also give $A$, the probability that a randomly chosen Gray run ends lower than a randomly chosen binary run (Vargha and Delaney, 2000); 0.5 means no difference. Effect Sizes and Standardized Differences derives the properties of $A$ and how precisely thirty runs per method estimate it. What the Rank-Sum Test Tests shows that $A$ is the quantity the Wilcoxon rank-sum test responds to, estimated by its $U$ statistic divided by the number of pairs.

Example (the cliff argument predicts the wrong winner on F1). The sphere's minimum sits exactly on the 8-bit cliff between 127 and 128, so the argument so far predicts that Gray coding does better on F1. The tables say otherwise: binary coding was as good or better on the sphere. The explanation after the tables is the most instructive part of the experiment.

The GA, 50 generations (1,000 evaluations):

Function Bits Binary Gray $A$
F1 8 0.00766 [0.00443, 0.0109] 0.0109 [0.00524, 0.0198] 0.35
F1 16 0.00578 [0.00277, 0.0131] 0.0181 [0.00823, 0.0271] 0.31
F2 8 0.0533 [0.0125, 0.207] 0.0287 [0.00936, 0.0886] 0.62
F2 16 0.125 [0.0312, 0.351] 0.110 [0.0193, 0.214] 0.60

The GA, 500 generations (10,000 evaluations):

Function Bits Binary Gray $A$
F1 8 0.00121 [0.00121, 0.00121] 0.00121 [0.00121, 0.00121] 0.45
F1 16 0.000534 [0.000251, 0.00100] 0.000609 [0.000258, 0.00129] 0.45
F2 8 0.00403 [0.00180, 0.00712] 0.00180 [0.00157, 0.0243] 0.55
F2 16 0.0306 [0.00162, 0.0816] 0.0162 [0.00182, 0.0669] 0.55

To separate the effect of the coding on mutation from everything else the GA does, the script also runs a $(1+1)$ evolutionary algorithm. It keeps a single string, mutates it by bit flips at rate $1/L$, and keeps the child if it is no worse.

The $(1+1)$ EA, 1,000 and 10,000 evaluations:

Function Bits Budget Binary Gray $A$
F1 16 1,000 1.83e-8 [1.83e-8, 1.83e-8] 3.11e-7 [6.71e-8, 5.55e-7] 0.10
F2 8 1,000 0.287 [0.0579, 1.02] 0.115 [0.0176, 0.168] 0.72
F2 16 1,000 0.538 [0.0548, 1.00] 0.104 [0.0214, 0.155] 0.69
F2 8 10,000 0.0107 [0.00227, 0.0821] 0.00739 [0.00302, 0.0256] 0.57
F2 16 10,000 0.110 [0.00650, 0.771] 0.0192 [0.00429, 0.0431] 0.73

Two F1 rows are omitted: 8 bits at either budget, and 16 bits at 10,000 evaluations. There every $(1+1)$ run under both codings ended at the best value the grid allows, $3 \times 0.020078^2 = 0.00121$ for 8 bits and $1.83 \times 10^{-8}$ for 16.

The results support Gray coding on one function and not on the other.

  • On Rosenbrock's function, Gray coding helped. It helped modestly in the GA ($A$ between 0.55 and 0.62) and more clearly in the $(1+1)$ EA ($A$ near 0.7), where its interquartile ranges were several times narrower. This fits the count of local minima above: under binary coding, a mutation-driven search on F2 has almost four times as many places to stall.
  • On the sphere, binary coding was as good or better. In the GA at 1,000 evaluations, Gray runs ended higher ($A$ = 0.31 and 0.35); at 10,000 evaluations the difference had nearly vanished. In the $(1+1)$ EA with 16 bits, all 30 binary runs reached the grid's best point within 1,000 evaluations, against 6 of the 30 Gray runs.

Why would the sphere favor the code with the cliff? Local minima do not explain it. Take one variable under binary coding. Within the half of the range where the leading bit is 1, all values are positive and $x^2$ grows with $k$. So turning any other 1 into a 0 lowers $k$, keeps it in that half, and improves fitness. Within the other half all values are negative, $x^2$ falls as $k$ grows, and turning any 0 after the leading bit into a 1 improves fitness. A string that no single flip improves must therefore be 10000000 or 01111111, the two grid points beside zero. But the same is true under Gray coding. By the reasoning of the general rule above, a string that no Gray flip improves has no better grid neighbor either, and on the grid only those two points have none. The script confirms that on the 8-bit grid both codes have exactly these two points, and no others, as the strings no single flip improves. So the count of local minima does not tell the two codes apart here.

A likely reason, which the experiment does not test, is how the bits interact. Under binary coding, within each half the right value of every lower bit is the same whatever the other bits are, as on OneMax: all 0 in the upper half and all 1 in the lower. Gray coding reflects the order of the lower bits whenever a higher bit changes. That ties the right value of each bit to the bits above it. The minimum also sits at the cliff, so binary coding never needs to cross it: either of the two grid points beside zero is optimal.

The sample is small, two functions and one GA. The GA itself was limited more by its weak selection than by its representation, as a binary GA on De Jong's test functions measures. What the experiment shows is that a Hamming cliff matters when a search needs to cross it. Gray coding's advantage, as Whitley's result suggests, is an advantage on average over functions rather than on each of them.

If the code itself can help or hurt, one response is not to encode real numbers in bits at all.

Real-valued representation

The alternative to encoding real variables in bits is not to encode them at all. A real-valued (floating-point) representation stores each variable as a number and uses operators defined on numbers. Mutation adds a small random perturbation, often Gaussian. Recombination mixes parent values arithmetically or samples around them. Eiben and Smith (2015, ch. 4) treat binary, integer, real-valued, permutation and tree representations in turn, each with its own mutation and recombination operators. They describe Gray coding as a way to repair the mismatch between bit flips and numeric distance under binary coding.

Direct representation removes the decoding step and the precision limit. It also puts mutation's step size under explicit control, which evolution strategies then adapt during the run. The standard real-valued operators, including blend crossover (BLX-$\alpha$) and simulated binary crossover, are described in crossover and mutation operators. Binary strings remain the natural choice where the decisions really are binary, as in selecting a subset of items or features. They also remain the object of study for the theory developed for bit strings.

What we have learned

A real variable becomes bits through a linear map whose step, $(U - L)/(2^n - 1)$, sets the precision; 11 bits give 0.01 on De Jong's interval. Under standard binary, adjacent values can sit a whole string apart, as 127 and 128 do on the 8-bit grid. The reflected Gray code puts every pair of grid neighbors one flip apart. It can therefore never add local minima to the grid, and on Rosenbrock's function it cut them from 226 under binary to 61. In the 30-seed experiment Gray coding helped on Rosenbrock's function and hurt on the sphere, as No Free Lunch says some function must.

The experiment also showed the assignment's GA held back by its selection more than by its code. The roulette wheel let selection pressure fade on OneMax in the simple genetic algorithm, too. Selection pressure and premature convergence measures how strongly each selection scheme favors the best, and describes what happens when a scheme favors them too much.

References

  • Caruana, R. A., and Schaffer, J. D. (1988). Representation and hidden bias: Gray vs. binary coding for genetic algorithms. In Proceedings of the Fifth International Conference on Machine Learning, 153–161. Morgan Kaufmann. record
  • De Jong, K. A. (1975). An Analysis of the Behavior of a Class of Genetic Adaptive Systems, appendix A. PhD dissertation, University of Michigan. record · 5 pages
  • Eiben, A. E., and Smith, J. E. (2015). Introduction to Evolutionary Computing, 2nd ed., chapter 4. Springer. record · 35 pages
  • Gray, F. (1953). Pulse code communication. U.S. Patent 2,632,058, issued March 17, 1953. record
  • Vargha, A., and Delaney, H. D. (2000). A critique and improvement of the CL common language effect size statistics of McGraw and Wong. Journal of Educational and Behavioral Statistics, 25(2), 101–132. record · 4 pages
  • Whitley, D. (1994). A genetic algorithm tutorial. Statistics and Computing, 4(2), 65–85. record · 2 pages
  • Whitley, D. (1999). A free lunch proof for Gray versus binary encodings. In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO 1999), 726–733. Morgan Kaufmann. record

Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 7 revisions