HOME

TheInfoList



OR:

In
information theory Information theory is the scientific study of the quantification (science), quantification, computer data storage, storage, and telecommunication, communication of information. The field was originally established by the works of Harry Nyquist a ...
, the Hamming distance between two strings of equal length is the number of positions at which the corresponding
symbol A symbol is a mark, sign, or word that indicates, signifies, or is understood as representing an idea, object, or relationship. Symbols allow people to go beyond what is known or seen by creating linkages between otherwise very different conc ...
s are different. In other words, it measures the minimum number of ''substitutions'' required to change one string into the other, or the minimum number of ''errors'' that could have transformed one string into the other. In a more general context, the Hamming distance is one of several
string metric In mathematics and computer science, a string metric (also known as a string similarity metric or string distance function) is a metric that measures distance ("inverse similarity") between two text strings for approximate string matching or comp ...
s for measuring the
edit distance In computational linguistics and computer science, edit distance is a string metric, i.e. a way of quantifying how dissimilar two strings (e.g., words) are to one another, that is measured by counting the minimum number of operations required to ...
between two sequences. It is named after the American mathematician
Richard Hamming Richard Wesley Hamming (February 11, 1915 – January 7, 1998) was an American mathematician whose work had many implications for computer engineering and telecommunications. His contributions include the Hamming code (which makes use of a Ha ...
. A major application is in
coding theory Coding theory is the study of the properties of codes and their respective fitness for specific applications. Codes are used for data compression, cryptography, error detection and correction, data transmission and data storage. Codes are stud ...
, more specifically to
block code In coding theory, block codes are a large and important family of error-correcting codes that encode data in blocks. There is a vast number of examples for block codes, many of which have a wide range of practical applications. The abstract defini ...
s, in which the equal-length strings are vectors over a
finite field In mathematics, a finite field or Galois field (so-named in honor of Évariste Galois) is a field that contains a finite number of elements. As with any field, a finite field is a set on which the operations of multiplication, addition, subtr ...
.


Definition

The Hamming distance between two equal-length strings of symbols is the number of positions at which the corresponding symbols are different.


Examples

The symbols may be letters, bits, or decimal digits, among other possibilities. For example, the Hamming distance between: * "kain" and "kain" is 3. * "krin" and "krin" is 3. * "kin" and "kin" is 4. * and is 4. * 2396 and 2396 is 3.


Properties

For a fixed length ''n'', the Hamming distance is a
metric Metric or metrical may refer to: * Metric system, an internationally adopted decimal system of measurement * An adjective indicating relation to measurement in general, or a noun describing a specific type of measurement Mathematics In mathem ...
on the set of the
word A word is a basic element of language that carries an semantics, objective or pragmatics, practical semantics, meaning, can be used on its own, and is uninterruptible. Despite the fact that language speakers often have an intuitive grasp of w ...
s of length ''n'' (also known as a
Hamming space In statistics and coding theory, a Hamming space (named after American mathematician Richard Hamming) is usually the set of all 2^N binary strings of length ''N''. It is used in the theory of coding signals and transmission. More generally, a Ham ...
), as it fulfills the conditions of non-negativity, symmetry, the Hamming distance of two words is 0 if and only if the two words are identical, and it satisfies the
triangle inequality In mathematics, the triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. This statement permits the inclusion of degenerate triangles, but ...
as well: Indeed, if we fix three words ''a'', ''b'' and ''c'', then whenever there is a difference between the ''i''th letter of ''a'' and the ''i''th letter of ''c'', then there must be a difference between the ''i''th letter of ''a'' and ''i''th letter of ''b'', or between the ''i''th letter of ''b'' and the ''i''th letter of ''c''. Hence the Hamming distance between ''a'' and ''c'' is not larger than the sum of the Hamming distances between ''a'' and ''b'' and between ''b'' and ''c''. The Hamming distance between two words ''a'' and ''b'' can also be seen as the
Hamming weight The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. It is thus equivalent to the Hamming distance from the all-zero string of the same length. For the most typical case, a string o ...
of ''a'' − ''b'' for an appropriate choice of the − operator, much as the difference between two integers can be seen as a distance from zero on the number line. For binary strings ''a'' and ''b'' the Hamming distance is equal to the number of ones ( population count) in ''a'' XOR ''b''. The metric space of length-''n'' binary strings, with the Hamming distance, is known as the ''Hamming cube''; it is equivalent as a metric space to the set of distances between vertices in a
hypercube graph In graph theory, the hypercube graph is the graph formed from the vertices and edges of an -dimensional hypercube. For instance, the cube graph is the graph formed by the 8 vertices and 12 edges of a three-dimensional cube. has vertices, e ...
. One can also view a binary string of length ''n'' as a vector in \mathbb^ by treating each symbol in the string as a real coordinate; with this embedding, the strings form the vertices of an ''n''-dimensional
hypercube In geometry, a hypercube is an ''n''-dimensional analogue of a square () and a cube (). It is a closed, compact, convex figure whose 1- skeleton consists of groups of opposite parallel line segments aligned in each of the space's dimensions, ...
, and the Hamming distance of the strings is equivalent to the
Manhattan distance A taxicab geometry or a Manhattan geometry is a geometry whose usual distance function or Metric (mathematics), metric of Euclidean geometry is replaced by a new metric in which the distance between two points is the sum of the absolute differences ...
between the vertices.


Error detection and error correction

The minimum Hamming distance is used to define some essential notions in
coding theory Coding theory is the study of the properties of codes and their respective fitness for specific applications. Codes are used for data compression, cryptography, error detection and correction, data transmission and data storage. Codes are stud ...
, such as error detecting and error correcting codes. In particular, a
code In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communication ...
''C'' is said to be ''k'' error detecting if, and only if, the minimum Hamming distance between any two of its codewords is at least ''k''+1. For example, consider the code consisting of two codewords "000" and "111". The hamming distance between these two words is 3, and therefore it is ''k''=2 error detecting. This means that if one bit is flipped or two bits are flipped, the error can be detected. If three bits are flipped, then "000" becomes "111" and the error can not be detected. A code ''C'' is said to be ''k-error correcting'' if, for every word ''w'' in the underlying Hamming space ''H'', there exists at most one codeword ''c'' (from ''C'') such that the Hamming distance between ''w'' and ''c'' is at most ''k''. In other words, a code is ''k''-errors correcting if, and only if, the minimum Hamming distance between any two of its codewords is at least 2''k''+1. This is more easily understood geometrically as any closed balls of radius ''k'' centered on distinct codewords being disjoint. These balls are also called ''
Hamming sphere In geometry, a sphere packing is an arrangement of non-overlapping spheres within a containing space. The spheres considered are usually all of identical size, and the space is usually three-dimensional Euclidean space. However, sphere packing p ...
s'' in this context. For example, consider the same 3 bit code consisting of two codewords "000" and "111". The Hamming space consists of 8 words 000, 001, 010, 011, 100, 101, 110 and 111. The codeword "000" and the single bit error words "001","010","100" are all less than or equal to the Hamming distance of 1 to "000". Likewise, codeword "111" and its single bit error words "110","101" and "011" are all within 1 Hamming distance of the original "111". In this code, a single bit error is always within 1 Hamming distance of the original codes, and the code can be ''1-error correcting'', that is ''k=1''. The minimum Hamming distance between "000" and "111" is 3, which satisfies ''2k+1 = 3''. Thus a code with minimum Hamming distance ''d'' between its codewords can detect at most ''d''-1 errors and can correct ⌊(''d''-1)/2⌋ errors. The latter number is also called the '' packing radius'' or the ''error-correcting capability'' of the code.


History and applications

The Hamming distance is named after
Richard Hamming Richard Wesley Hamming (February 11, 1915 – January 7, 1998) was an American mathematician whose work had many implications for computer engineering and telecommunications. His contributions include the Hamming code (which makes use of a Ha ...
, who introduced the concept in his fundamental paper on Hamming codes, ''Error detecting and error correcting codes'', in 1950. Hamming weight analysis of bits is used in several disciplines including
information theory Information theory is the scientific study of the quantification (science), quantification, computer data storage, storage, and telecommunication, communication of information. The field was originally established by the works of Harry Nyquist a ...
,
coding theory Coding theory is the study of the properties of codes and their respective fitness for specific applications. Codes are used for data compression, cryptography, error detection and correction, data transmission and data storage. Codes are stud ...
, and
cryptography Cryptography, or cryptology (from grc, , translit=kryptós "hidden, secret"; and ''graphein'', "to write", or ''-logia'', "study", respectively), is the practice and study of techniques for secure communication in the presence of adver ...
. It is used in
telecommunication Telecommunication is the transmission of information by various types of technologies over wire, radio, optical, or other electromagnetic systems. It has its origin in the desire of humans for communication over a distance greater than that fe ...
to count the number of flipped bits in a fixed-length binary word as an estimate of error, and therefore is sometimes called the signal distance. For ''q''-ary strings over an
alphabet An alphabet is a standardized set of basic written graphemes (called letters) that represent the phonemes of certain spoken languages. Not all writing systems represent language in this way; in a syllabary, each character represents a syll ...
of size ''q'' ≥ 2 the Hamming distance is applied in case of the q-ary symmetric channel, while the
Lee distance In coding theory, the Lee distance is a distance between two strings x_1 x_2 \dots x_n and y_1 y_2 \dots y_n of equal length ''n'' over the ''q''-ary alphabet of size . It is a metric defined as \sum_^n \min(, x_i - y_i, ,\, q - , x_i - y_i, ). I ...
is used for phase-shift keying or more generally channels susceptible to synchronization errors because the Lee distance accounts for errors of ±1. If q = 2 or q = 3 both distances coincide because any pair of elements from \mathbb/2\mathbb or \mathbb/3\mathbb differ by 1, but the distances are different for larger q. The Hamming distance is also used in
systematics Biological systematics is the study of the diversification of living forms, both past and present, and the relationships among living things through time. Relationships are visualized as evolutionary trees (synonyms: cladograms, phylogenetic tre ...
as a measure of genetic distance. However, for comparing strings of different lengths, or strings where not just substitutions but also insertions or deletions have to be expected, a more sophisticated metric like the
Levenshtein distance In information theory, linguistics, and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-charac ...
is more appropriate.


Algorithm example

The following function, written in Python 3, returns the Hamming distance between two strings: def hamming_distance(string1, string2): if (len(string1) != len(string2)): raise Exception('Strings must be of equal length.') dist_counter = 0 for n in range(len(string1)): if string1 != string2 dist_counter += 1 return dist_counter Or, in a shorter expression: sum(xi != yi for xi, yi in zip(x, y)) The function hamming_distance(), implemented in
Python 3 The programming language Python was conceived in the late 1980s, and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to ABC capable of exception handling and interfacing with th ...
, computes the Hamming distance between two strings (or other iterable objects) of equal length by creating a sequence of Boolean values indicating mismatches and matches between corresponding positions in the two inputs, then summing the sequence with True and False values, interpreted as one and zero, respectively. def hamming_distance(s1, s2) -> int: """Return the Hamming distance between equal-length sequences.""" if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length.") return sum(el1 != el2 for el1, el2 in zip(s1, s2)) where th
zip()
function merges two equal-length collections in pairs. The following C function will compute the Hamming distance of two integers (considered as binary values, that is, as sequences of bits). The running time of this procedure is proportional to the Hamming distance rather than to the number of bits in the inputs. It computes the bitwise
exclusive or Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false). It is symbolized by the prefix operator J and by the infix operators XOR ( or ), EOR, EXOR, , ...
of the two inputs, and then finds the
Hamming weight The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. It is thus equivalent to the Hamming distance from the all-zero string of the same length. For the most typical case, a string o ...
of the result (the number of nonzero bits) using an algorithm of that repeatedly finds and clears the lowest-order nonzero bit. Some compilers support the __builtin_popcount function which can calculate this using specialized processor hardware where available. int hamming_distance(unsigned x, unsigned y) A faster alternative is to use the population count (''popcount'') assembly instruction. Certain compilers such as GCC and Clang make it available via an intrinsic function: // Hamming distance for 32-bit integers int hamming_distance32(unsigned int x, unsigned int y) // Hamming distance for 64-bit integers int hamming_distance64(unsigned long long x, unsigned long long y)


See also

*
Closest string In theoretical computer science, the closest string is an NP-hard computational problem, which tries to find the geometrical center of a set of input strings. To understand the word "center", it is necessary to define a distance between two string ...
*
Damerau–Levenshtein distance In information theory and computer science, the Damerau–Levenshtein distance (named after Frederick J. Damerau and Vladimir I. Levenshtein.) is a string metric for measuring the edit distance between two sequences. Informally, the Damerau–Leve ...
*
Euclidean distance In mathematics, the Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefor ...
*
Gap-Hamming problem In communication complexity, the gap-Hamming problem asks, if Alice and Bob are each given a (potentially different) string, what is the minimal number of bits that they need to exchange in order for Alice to approximately compute the Hamming dist ...
* Gray code *
Jaccard index The Jaccard index, also known as the Jaccard similarity coefficient, is a statistic used for gauging the similarity and diversity of sample sets. It was developed by Grove Karl Gilbert in 1884 as his ratio of verification (v) and now is freque ...
*
Levenshtein distance In information theory, linguistics, and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-charac ...
* Mahalanobis distance * Mannheim distance * Sørensen similarity index *
Sparse distributed memory Sparse distributed memory (SDM) is a mathematical model of human long-term memory introduced by Pentti Kanerva in 1988 while he was at NASA Ames Research Center. It is a generalized random-access memory (RAM) for long (e.g., 1,000 bit) binary words. ...
*
Word ladder Word ladder (also known as Doublets, word-links, change-the-word puzzles, paragrams, laddergrams, or word golf) is a word game invented by Lewis Carroll. A word ladder puzzle begins with two words, and to solve the puzzle one must find a chain of o ...


References


Further reading

* * * {{Authority control String metrics Coding theory Articles with example Python (programming language) code Articles with example C++ code Metric geometry Cubes