Wave function: Difference between revisions

From formulasearchengine
Jump to navigation Jump to search
Line 1: Line 1:
{{Refimprove|date=February 2012}}
Hello! <br>My name is Chadwick and I'm a 25 years old boy from Italy.<br><br>my site ... [http://Www.A-Dash.org/userinfo.php?uid=368877 Fifa 15 coin generator]
[[Image:XOR Swap.svg|thumb|upright=2|alt=With three XOR operations the binary values 1010 and 0011 are exchanged between variables.|Using the XOR swap algorithm to exchange [[nibble]]s between variables without the use of temporary storage]]
 
In [[computer programming]], the '''XOR swap''' is an [[algorithm]] that uses the [[exclusive disjunction|XOR]] [[bitwise operation]] to [[swap (computer science)|swap]] values of distinct [[variable (programming)|variable]]s having the same [[data type]] without using a temporary variable. "Distinct" means that the variables are stored at different memory addresses; the actual values of the variables do not have to be different.
 
==The algorithm==
Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:
<syntaxhighlight lang="pascal">
X := X XOR Y
Y := X XOR Y
X := X XOR Y
</syntaxhighlight>
The algorithm typically corresponds to three [[machine code]] instructions. Since XOR is a [[commutative operation]], X XOR Y can be replaced with Y XOR X in any of the lines. When coded in assembly language, this commutativity is often exercised in the second line:
 
{| class="wikitable" style="width: 45em;"
|-
! Pseudocode !! IBM [[System/370]] assembly !! x86 assembly
|-
| {{code|1=X := X XOR Y|2=pascal}} || {{code|1=XR    R1,R2|2=asm}} || {{code|1=xor    eax, ebx|2=asm}}
|-
| {{code|1=Y := X XOR Y|2=pascal}} || {{code|1=XR    R2,R1|2=asm}} || {{code|1=xor    ebx, eax|2=asm}}
|-
| {{code|1=X := X XOR Y|2=pascal}} || {{code|1=XR    R1,R2|2=asm}} || {{code|1=xor    eax, ebx|2=asm}}
|}
 
In the above System/370 assembly code sample, R1 and R2 are distinct [[processor register|register]]s, and each XR operation leaves its result in the register named in the first argument. Using x86 assembly, values X and Y are in registers eax and ebx (respectively), and {{code|xor|2=asm}} places the result of the operation in the first register.
 
However, the algorithm fails if ''x'' and ''y'' use the same storage location, since the value stored in that location will be zeroed out by the first XOR instruction, and then remain zero; it will not be "swapped with itself". Note that this is ''not'' the same as if ''x'' and ''y'' have the same values.  The trouble only comes when ''x'' and ''y'' use the same storage location, in which case their values must already be equal. That is, if ''x'' and ''y'' use the same storage location, then the line:
<syntaxhighlight lang="pascal">
X := X XOR Y
</syntaxhighlight>
sets ''x'' to zero (because ''x'' = ''y'' so X XOR Y is zero) ''and'' sets ''y'' to zero (since it uses the same storage location), causing ''x'' and ''y'' to lose their original values.
 
==Proof of correctness==
The [[binary operation]] XOR over bit strings of length <math>N</math> exhibits the following properties (where <math>\oplus</math> denotes XOR):<ref>
The first three properties, along with the existence of an inverse for each element, are the definition of an [[Abelian group]]. The last property is a structural feature of XOR not necessarily shared by other Abelian groups.
</ref>
* '''L1.''' [[Commutative operation|Commutativity]]: <math>A \oplus B = B \oplus A</math>
* '''L2.''' [[Associativity]]: <math>(A \oplus B) \oplus C = A \oplus (B \oplus C)</math>
* '''L3.''' [[Identity element|Identity exists]]: there is a bit string, 0, (of length ''N'') such that <math>A \oplus 0 = A</math> for any <math>A</math>
* '''L4.''' Each element is its own [[inverse element|inverse]]: for each <math>A</math>, <math>A \oplus A = 0</math>.
 
Suppose that we have two distinct registers <code>R1</code> and <code>R2</code> as in the table below, with initial values ''A'' and ''B'' respectively. We perform the operations below in sequence, and reduce our results using the properties listed above.
 
{| class="wikitable"
|-
! Step
! Operation
! Register 1
! Register 2
! Reduction
|-
| 0 || Initial value || <math>\ A</math> || <math>\ B</math> || —
|-
| 1 || <code>R1 := R1 XOR R2</code>  || <math>\ A \oplus B</math> || <math>\ B</math> || —
|-
| 2 || <code>R2 := R1 XOR R2</code>  || <math>\ A \oplus B</math> || <math>\begin{align} (A \oplus B) \oplus B =& A \oplus (B \oplus B) \\=& A \oplus 0 \\=& A \end{align}</math> || '''L2<br> L4<br> L3'''
|-
| 3 || <code>R1 := R1 XOR R2</code>  || <math>\begin{align} (A \oplus B) \oplus A =& A \oplus (A \oplus B) \\=& (A \oplus A) \oplus B \\=& 0 \oplus B \\=& B \end{align}</math> || <math>\ A</math> || '''L1<br> L2<br> L4<br> L3'''
|-
|}
 
=== Linear algebra interpretation ===
As XOR can be interpreted as binary addition and a pair of values can be interpreted as a point in two-dimensional space, the steps in the algorithm can be interpreted as 2&times;2 matrices with binary values. For simplicity, assume initially that ''x'' and ''y'' are each single bits, not bit vectors.
 
For example, the step:
<syntaxhighlight lang="pascal">
X := X XOR Y
</syntaxhighlight>
which also has the implicit:
<syntaxhighlight lang="pascal">
Y := Y
</syntaxhighlight>
corresponds to the matrix <math>\left(\begin{smallmatrix}1 & 1\\0 & 1\end{smallmatrix}\right)</math> as
:<math>\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix} \begin{pmatrix}x\\y\end{pmatrix}
= \begin{pmatrix}x+y\\y\end{pmatrix}.
</math>
The sequence of operations is then expressed as:
:<math>
\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix}
\begin{pmatrix}1 & 0\\1 & 1\end{pmatrix}
\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix}
=
\begin{pmatrix}0 & 1\\1 & 0\end{pmatrix}
</math>
(working with binary values, so <math>1 + 1 = 0</math>), which expresses the [[elementary matrix]] of switching two rows (or columns) in terms of the [[Shear mapping|transvections]] (shears) of adding one element to the other.
 
To generalize to where X and Y are not single bits, but instead bit vectors of length ''n'', these 2&times;2 matrices are replaced by 2''n''&times;2''n'' [[block matrices]] such as <math>\left(\begin{smallmatrix}I_n & I_n\\0 & I_n\end{smallmatrix}\right).</math>
 
Note that these matrices are operating on ''values,'' not on ''variables'' (with storage locations), hence this interpretation abstracts away from issues of storage location and the problem of both variables sharing the same storage location.
 
==Code example==
A [[C (programming language)|C]] function that implements the XOR swap algorithm:
<!-- This display template is broken in IE 6, the top half of the pretty bordered box is cut off. -->
<source lang="c">
void xorSwap (int *x, int *y) {
    if (x != y) {
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}
</source>
Note that the code does not swap the integers passed immediately, but first checks if their addresses are distinct. This is because, if the addresses are equal, the algorithm will fold to a triple *x ^= *x resulting in zero.
 
The body of this function is sometimes incorrectly shortened to <code>if (x != y) *x^=*y^=*x^=*y;</code>. This code has undefined behavior, since it modifies the [[Value (computer science)|lvalue]] <code>*x</code> twice without an intervening [[sequence point]].
 
==Reasons for use in practice==
In most practical scenarios, the trivial swap algorithm using a temporary register is more efficient. Limited situations in which XOR swapping may be practical include:
* On a processor where the instruction set encoding permits the XOR swap to be encoded in a smaller number of bytes;
* In a region with high [[register pressure]], it may allow the [[register allocator]] to avoid spilling a register.
* In [[microcontrollers]] where available RAM is very limited.
 
Because these situations are rare, most optimizing compilers do not generate XOR swap code.
 
==Reasons for avoidance in practice==
Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster. The XOR swap is also much less readable and completely opaque to anyone unfamiliar with the technique.
 
On modern [[CPU architecture]]s, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via [[instruction pipeline]]s. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture.
 
===Aliasing===
The XOR swap is also complicated in practice by [[aliasing (computing)|aliasing]]. As noted above, if an attempt is made to XOR-swap the contents of some location with itself, the result is that the location is zeroed out and its value lost. Therefore, XOR swapping must not be used blindly in a high-level language if aliasing is possible.
 
Similar problems occur with [[call by name]], as in [[Jensen's Device]], where swapping <code>i</code> and <code>A[i]</code> via a temporary variable yields incorrect results due to the arguments being related: swapping via <code>temp = i; i = A[i]; A[i] = temp</code> changes the value for <code>i</code> in the second statement, which then results in the incorrect lvalue for <code>A[i]</code> in the third statement.
 
==Variations==
The underlying principle of the XOR swap algorithm can be applied to any operation meeting criteria L1 through L4 above. Replacing XOR by addition and subtraction gives a slightly different, but largely equivalent, formulation:
 
<source lang="c">
void addSwap (unsigned int *x, unsigned int *y)
{
    if (x != y) {
        *x = *x + *y;
        *y = *x - *y;
        *x = *x - *y;
    }
}
</source>
 
Unlike the XOR swap, this variation requires that the underlying processor or programming language uses a method such as [[modular arithmetic]] or [[bignum]]s to guarantee that the computation of <code>X + Y</code> cannot cause an error due to [[integer overflow]]. Therefore, it is seen even more rarely in practice than the XOR swap.
 
Note, however, that the implementation of <code>addSwap</code> above in the C programming language always works even in case of integer overflow, since, according to the C standard, addition and  subtraction of unsigned integers follow the rules of [[modular arithmetic]], i. e. are done in the [[cyclic group]] <math>\mathbb Z/2^s\mathbb Z</math> where <math>s</math> is the number of bits of <code>unsigned int</code>. Indeed, the correctness of the algorithm follows from the fact that the formulas <math>(x + y) - y = x</math> and <math>(x + y) - ((x + y) - y) = y</math> hold in any [[abelian group]]. This is actually a generalization of the proof for the XOR swap algorithm: XOR is both the addition and subtraction in the abelian group <math>(\mathbb Z/2\mathbb Z)^{s}</math>.
 
== Notes ==
<references/>
 
==See also==
*[[Symmetric difference]]
*[[XOR linked list]]
*[[Feistel cipher]] (the XOR swap algorithm is a degenerate form of a Feistel cypher)
 
[[Category:Algorithms]]
[[Category:Articles with example C code]]
[[Category:Binary arithmetic]]
 
[[pl:Zamiana wartości zmiennych]]
[[fr:Échange (informatique)#En_utilisant_l.27op.C3.A9ration_XOR]]

Revision as of 18:53, 11 February 2014

Hello!
My name is Chadwick and I'm a 25 years old boy from Italy.

my site ... Fifa 15 coin generator