Comparison (computer programming)
Encyclopedia
In computer programming
, comparison of two data items is effected by the comparison operators typically written as:
These operators produce the logical value
the statements following
Some programming languages make a syntactical distinction between the "equals" of assignment
(e.g.
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
, comparison of two data items is effected by the comparison operators typically written as:
- > (greater than)
- < (less than)
- >= (greater than or equal to)
- <= (less than or equal to)
- = or (exactly equal to)
- !=, <>, ~= or /= (not equal to)
These operators produce the logical value
true
or false
, depending on the result of the comparison. For example, in the pseudo-codeif a > 1 then ...
the statements following
then
are executed only if the value of the variable "a" is greater than 1 (i.e. when the logical value of a > 1
is true
).Some programming languages make a syntactical distinction between the "equals" of assignment
Assignment (computer science)
In computer programming, an assignment statement sets or re-sets the value stored in the storage location denoted by a variable name. In most imperative computer programming languages, assignment statements are one of the basic statements...
(e.g.
a = 1
assigns the value 1 to the variable "a") and the "equals" of comparison (if a 1 then ...). Other languages determine which is meant from context.
"Greater than" and "less than" comparison of non-numeric data is performed according to a sort convention (such as, for text strings, lexicographical orderLexicographical orderIn mathematics, the lexicographic or lexicographical order, , is a generalization of the way the alphabetical order of words is based on the alphabetical order of letters.-Definition:Given two partially ordered sets A and B, the lexicographical order on...
) which may be built in to the programming language and/or configurable by the programmer.
When it is desired to associate a numeric value with the result of a comparison between two data items, say "a" and "b", the usual convention is to assign −1 if a < b, 0 if a = b and 1 if a > b. For example, the C function strcmp
performs a three-way comparisonThree-way comparisonIn computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A B in a single operation, in accordance with the mathematical law of trichotomy.- Machine-level computation :...
and returns −1, 0, or 1 according to this convention, and qsort expects the comparison function to return values according to this convention. In sorting algorithmSorting algorithmIn computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order...
s, the efficiency of comparison code is critical since it is one of the major factors contributing to sorting performance.
In floating-point arithmetic, numbers, including many simple fractionFraction (mathematics)A fraction represents a part of a whole or, more generally, any number of equal parts. When spoken in everyday English, we specify how many parts of a certain size there are, for example, one-half, five-eighths and three-quarters.A common or "vulgar" fraction, such as 1/2, 5/8, 3/4, etc., consists...
s, cannot be represented exactly, and it may be necessary to test for equality within a given tolerance. For example, rounding errors may mean that the comparison in
a = 1/7
if a*7 = 1 then ...
unexpectedly evaluates false
. Typically this problem is handled by rewriting the comparison as if abs(a*7 - 1) < tolerance then ..., where tolerance
is a suitably tiny number and abs
is the absolute valueAbsolute valueIn mathematics, the absolute value |a| of a real number a is the numerical value of a without regard to its sign. So, for example, the absolute value of 3 is 3, and the absolute value of -3 is also 3...
function.
Comparison of programmer-defined data typeData typeIn computer programming, a data type is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of...
s (data types of which the programming language itself has no in-built understanding) may be carried out by custom-written or library functions (such as strcmp
mentioned above), or, in some languages, by "overloadingOperator overloadingIn object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
" a comparison operator – that is, assigning a programmer-defined meaning that depends on the data types being compared.
Sometimes, particularly in object-oriented programmingObject-oriented programmingObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, the comparison raises questions of data typeData typeIn computer programming, a data type is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of...
s and inheritanceInheritance (computer science)In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
, equality and identityIdentity (mathematics)In mathematics, the term identity has several different important meanings:*An identity is a relation which is tautologically true. This means that whatever the number or value may be, the answer stays the same. For example, algebraically, this occurs if an equation is satisfied for all values of...
. It is often necessary to distinguish between:
- two objects with different datatypes both related to another datatype, e.g. an orange and a lemon, both being citrus fruit
- two different objects of the same type, e.g. two hands
- two objects being equal but distinct, e.g. two $10 banknotes
- two different references to the same object, e.g. two nicknames for the same person
Sameness and difference can be relative or graduated as well as absolute, particularly in fuzzy logicFuzzy logicFuzzy logic is a form of many-valued logic; it deals with reasoning that is approximate rather than fixed and exact. In contrast with traditional logic theory, where binary sets have two-valued logic: true or false, fuzzy logic variables may have a truth value that ranges in degree between 0 and 1...
, artificial intelligenceArtificial intelligenceArtificial intelligence is the intelligence of machines and the branch of computer science that aims to create it. AI textbooks define the field as "the study and design of intelligent agents" where an intelligent agent is a system that perceives its environment and takes actions that maximize its...
, signal processingSignal processingSignal processing is an area of systems engineering, electrical engineering and applied mathematics that deals with operations on or analysis of signals, in either discrete or continuous time...
, lossy data compressionLossy data compressionIn information technology, "lossy" compression is a data encoding method that compresses data by discarding some of it. The procedure aims to minimize the amount of data that need to be held, handled, and/or transmitted by a computer...
and pattern recognitionPattern recognitionIn machine learning, pattern recognition is the assignment of some sort of output value to a given input value , according to some specific algorithm. An example of pattern recognition is classification, which attempts to assign each input value to one of a given set of classes...
.
See also
- Relational operatorRelational operatorIn computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities...
- Regular expressionRegular expressionIn computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...
- Comparison of programming languagesComparison of programming languagesProgramming languages are used for controlling the behavior of a machine . Like natural languages, programming languages conform to rules for syntax and semantics.There are thousands of programming languages and new ones are created every year...