Meta tags:
description= The essential linear algebra you need for quantum computing: vectors, matrices, tensor products, and inner products, explained with quantum computing…;
author= QuantumComputingCourses.com;
Headings (most frequently used words):
quantum, and, matrices, matrix, product, vectors, complex, inner, products, tensor, the, algebra, for, as, states, numbers, why, gate, multiplication, pauli, properties, confusing, with, linear, computing, they, matter, gates, probabilities, composition, multi, qubit, systems, hermitian, observables, commutators, density, common, mistakes, this, matters, next, steps, try, it, yourself, python, playground, related, tutorials, get, one, email, week, column, row, dirac, notation, four, unitary, fidelity, between, cnot, spectral, decomposition, partial, trace, entanglement, order, forgetting, conjugate, in, using, real, dtypes, when, are, needed, state, norm, ready, to, go, deeper, learn, reference, careers, about,
Text of the page (most frequently used words):
the (171), #complex (104), print (82), dtype (81), and (74), array (74), quantum (71), psi (70), state (62), qubit (48), product (46), sqrt (46), #matrix (43), ket_0 (40), for (35), are (35), gate (34), matrices (33), phi (29), states (28), this (26), numpy (26), conj (26), inner (25), ket_1 (25), with (24), true (24), you (23), two (23), computing (22), kron (22), tensor (21), import (21), trace (19), real (18), hermitian (18), products (17), eigenvalues (17), allclose (17), pauli (16), cnot (16), vectors (15), density (15), that (14), basis (14), mixed (14), unitary (14), pure (14), can (13), fidelity (13), all (12), courses (12), read (12), bell (12), algebra (12), vector (12), gates (11), has (11), abs (11), conjugate (11), from (10), guide (10), one (10), measurement (10), every (10), linear (10), outer (10), identity (10), hadamard (9), tutorials (9), why (9), norm (9), result (9), purity (9), 500 (9), 70710678 (9), min (8), numbers (8), they (8), these (8), have (8), 2x2 (8), both (8), then (8), rho (8), single (8), commutator (8), eye (8), eigenvectors (8), linalg (8), flip (8), projector (8), algorithm (7), systems (7), multiplication (7), probabilities (7), circuit (7), bra (7), probability (7), always (7), which (7), when (7), left (7), 000 (7), plus (7), qubits (7), apply (7), transpose (7), between (7), any (6), multi (6), first (6), not (6), right (6), ket (6), observable (6), partial (6), outcomes (6), but (6), same (6), ket_00 (6), rho_mixed (6), rho_pure (6), equal (6), classical (6), return (6), def (6), commute (6), phase (6), where (6), their (6), each (6), target (6), name (6), terms (5), 2026 (5), com (5), about (5), hardware (5), framework (5), qiskit (5), entanglement (5), python (5), commutators (5), observables (5), there (5), also (5), notation (5), decomposition (5), spectral (5), squared (5), shape (5), error (5), wrong (5), correct (5), combined (5), reduced (5), ket_11 (5), its (5), sum (5), vec (5), applying (5), control (5), noisy_plus (5), inner_product (5), use (4), bloch (4), sphere (4), learning (4), written (4), zeitgeist (4), donovan (4), get (4), how (4), related (4), next (4), matters (4), matter (4), tutorial (4), other (4), here (4), full (4), amplitudes (4), mathematical (4), spaces (4), number (4), different (4), operations (4), 4x4 (4), dimension (4), zeros (4), means (4), rho_q0_product (4), over (4), rho_q0 (4), own (4), properties (4), them (4), system (4), anticommutator (4), anti (4), operators (4), measures (4), lam (4), example (4), e_i (4), measuring (4), important (4), after (4), applied (4), sigma (4), gives (4), det (4), col_1 (4), col_0 (4), column (4), form (4), four (4), bit (4), hello (4), world (4), policy (3), amazon (3), team (3), careers (3), programming (3), glossary (3), case (3), studies (3), frameworks (3), free (3), who (3), writes (3), new (3), taking (3), what (3), cirq (3), pennylane (3), time (3), beginner (3), steps (3), common (3), mistakes (3), composition (3), browse (3), since (3), built (3), because (3), code (3), explained (3), theorem (3), ordering (3), order (3), individual (3), distinct (3), combines (3), space (3), imaginary (3), would (3), float (3), difference (3), before (3), operation (3), must (3), rightmost (3), reshape (3), maximally (3), entangled (3), called (3), superposition (3), commutation (3), columns (3), eigh (3), lambda_i (3), mechanics (3), outcome (3), expectation (3), need (3), most (3), ket_10 (3), ket_01 (3), controlled (3), lives (3), magnitude (3), inverse (3), original_ip (3), transformed_ip (3), equals (3), is_unitary (3), plus_y (3), plus_x (3), alpha (3), beta (3), prerequisites (3), braket (3), cookies (2), your (2), experience (2), affiliate (2), quantumcomputingcourses (2), books (2), podcasts (2), events (2), faq (2), editorial (2), jobs (2), interview (2), certifications (2), salary (2), timeline (2), types (2), reference (2), news (2), compare (2), paths (2), learn (2), research (2), industry (2), references (2), tools (2), quantumcomputing (2), email (2), worth (2), week (2), reaching (2), point (2), bernstein (2), vazirani (2), implementing (2), hidden (2), string (2), finder (2), inequalities (2), chsh (2), test (2), know (2), language (2), level (2), search (2), intermediate (2), guides (2), coursera (2), edx (2), udemy (2), brilliant (2), more (2), ibm (2), out (2), should (2), physics (2), run (2), entirely (2), try (2), yourself (2), playground (2), essential (2), place (2), uses (2), maps (2), described (2), magnitudes (2), 7071067811865476 (2), non (2), confusing (2), into (2), larger (2), good_state (2), container (2), works (2), bad_state (2), silently (2), parts (2), value (2), needed (2), wrong_ip (2), correct_ip (2), conjugating (2), entries (2), forgetting (2), makes (2), expression (2), diagrams (2), goes (2), purity_product (2), axis2 (2), axis1 (2), rho_product (2), rho_bell (2), compute (2), purity_mixed (2), purity_pure (2), valid (2), satisfies (2), check (2), give (2), coherences (2), does (2), uncertainty (2), far (2), useful (2), involves (2), algorithms (2), commuting (2), whether (2), hamiltonian (2), relations (2), several (2), practical (2), prob (2), zip (2), z_reconstructed (2), corresponding (2), tells (2), average (2), is_hermitian (2), physical (2), measure (2), multiplications (2), take (2), property (2), h_i (2), produces (2), flipped (2), output (2), flips (2), h_on_q0 (2), product_state (2), kronecker (2), computed (2), cnot_exact (2), cnot_decomposed (2), acts (2), step2 (2), step1 (2), noisy (2), prob_1 (2), prob_0 (2), normalization (2), overlap (2), norm_after (2), norm_before (2), preserves (2), row_1 (2), row_0 (2), orthonormal (2), unitarity (2), paulis (2), eigvals (2), leaves (2), unchanged (2), swaps (2), tol (2), result2 (2), physically (2), produce (2), amplitude (2), precise (2), satisfy (2), none (2), bra_psi (2), row (2), dirac (2), norm_squared (2), computational (2), ideas (2), wave (2), accept, decline, improve, track, performance, see, our, cookie, privacy, disclosure, llc, associate, earn, qualifying, purchases, contact, site, talent, pool, post, job, training, questions, cheatsheets, history, docs, maintained, curated, anyone, 241, 220, 112, subscribe, address, changed, spam, unsubscribe, anytime, paid, sept, updated, glance, page, walks, annealing, based, previous, continue, structured, ready, deeper, share, yes, was, helpful, quantumzeitgeist, ran, his, 2018, put, subject, down, material, forced, choice, nobody, make, pop, science, hand, waving, end, phd, ramp, had, usually, stopped, working, found, preloaded, edit, execute, instantly, runs, browser, signup, install, open, screen, tour, standard, set, physicist, shorthand, above, foundations, papers, understand, simulators, actually, under, hood, circuits, reversed, detected, through, decoherence, come, unit, concept, directly, 5000, generally, 0000, negative, composes, very, things, expanding, applies, operator, within, keeping, fixed, part, preserved, safe, raise, store, dangerous, drops, discards, assign, typed, using, dtypes, missing, requires, false, flows, draw, sits, touch, pitfalls, frequently, trip, people, expected, confirms, unentangled, yield, definite, neither, well, defined, lets, tracing, positive, semidefiniteness, notice, even, though, off, diagonal, elements, distinguish, nonzero, mixture, represents, weighted, discussed, represented, arise, provide, unified, zero, gradient, generators, parameterized, variational, stabilizer, codes, sets, detectable, stabilizers, correction, depends, trotter, trotterization, simulation, contexts, 2iz, 2ix, 2iy, beautiful, algebraic, structure, meaning, either, global, whose, eigenstates, reconstruct, sum_i, central, yields, mix, quantity, correspond, possible, computationally, separate, independently, rather, than, doing, mean, identities, simultaneously, preparation, create, starting, followed, action, only, h_on_q1, via, combine, joint, astype, diag, decomposed, again, convention, explains, look, backwards, compared, expressions, step, another, corresponds, subtlety, last, hits, later, generalizes, distance, provides, complementary, normalize, ideal, approximation, partially, overlapping, orthogonal, identical, close, simply, connects, born, rule, orthogonality, dot, encodes, dotting, preservation, reason, evolution, reversible, unlike, logic, discard, information, preserve, undo, norms, isclose, transformed, original, determinant, rows, understanding, buys, implies, fact, decompositions, appear, everywhere, combination, extends, eigvalsh, eigenvalue, multiplicity, multiplies, while, phases, analogous, nothing, eigenvector, clear, interpretation, together, atol, len, times, guarantees, vice, versa, creates, square, transforms, multiplying, unavoidable, yet, measured, bases, second, without, reduces, probabilistic, gottesman, knill, connection, might, wonder, just, convenience, require, describe, distinguishable, consider, projectors, itself, projects, onto, 70710678j, physicists, compact, way, write, element, coefficients, condition, dimensional, conventionally, description, covers, core, studying, block, verify, results, longer, worked, treatment, shorter, backed, pass, sections, background, basic, variables, functions, loops, math, mind, jan, series, concepts, home, troubleshooting, prep, universities, career, cheat, sheets, migration, comparison, pinball, explore, ocean, tket, pyquil, shor, grover, rigetti, quera, azure, quantinuum, ionq, google, providers, course, platforms, skip, main, content,
Text of the page (random words):
numpy as np i np eye 2 dtype complex h 1 np sqrt 2 np array 1 1 1 1 dtype complex x np array 0 1 1 0 dtype complex ket_0 np array 1 0 dtype complex apply h then x the combined matrix is x h step1 h ket_0 h 0 step2 x step1 x combined x h ket_0 same result in one step print np allclose step2 combined true this ordering convention explains why quantum circuit diagrams which read left to right look backwards compared to matrix expressions where the rightmost matrix acts first here is a practical example the cnot gate can be decomposed as hadamard on the target then a controlled z then hadamard on the target again import numpy as np i np eye 2 dtype complex h 1 np sqrt 2 np array 1 1 1 1 dtype complex h on qubit 1 the target qubit h2 np kron i h controlled z gate cz np diag 1 1 1 1 astype complex cnot i x h cz i x h cnot_decomposed h2 cz h2 cnot_exact np array 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 dtype complex print np allclose cnot_decomposed cnot_exact true tensor products for multi qubit systems when you combine two qubits the joint state lives in a space that is the tensor product of the two individual spaces a two qubit system has dimension 4 an n qubit system has dimension 2 n in numpy the tensor product kronecker product is computed with np kron import numpy as np ket_0 np array 1 0 dtype complex ket_1 np array 0 1 dtype complex two qubit basis states via kronecker product ket_00 np kron ket_0 ket_0 1 0 0 0 ket_01 np kron ket_0 ket_1 0 1 0 0 ket_10 np kron ket_1 ket_0 0 0 1 0 ket_11 np kron ket_1 ket_1 0 0 0 1 product state qubit 0 in qubit 1 in 0 plus np array 1 np sqrt 2 1 np sqrt 2 dtype complex product_state np kron plus ket_0 print product_state 0 70710678 0 j 0 0 j 0 70710678 0 j 0 0 j to apply a single qubit gate to one qubit in a multi qubit system tensor it with the identity on the other qubits i np eye 2 dtype complex h 1 np sqrt 2 np array 1 1 1 1 dtype complex hadamard on qubit 0 identity on qubit 1 h_on_q0 np kron h i identity on qubit 0 hadamard on qubit 1 h_on_q1 np kron i h print h_on_q0 shape 4 4 the cnot gate the controlled not cnot gate is the most important two qubit gate it flips the target qubit if and only if the control qubit is 1 the full 4x4 matrix is import numpy as np ket_0 np array 1 0 dtype complex ket_1 np array 0 1 dtype complex ket_00 np kron ket_0 ket_0 ket_01 np kron ket_0 ket_1 ket_10 np kron ket_1 ket_0 ket_11 np kron ket_1 ket_1 cnot np array 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 dtype complex cnot action on each basis state for name state in 00 ket_00 01 ket_01 10 ket_10 11 ket_11 output cnot state print f cnot name output real cnot 00 1 0 0 0 control 0 no flip cnot 01 0 1 0 0 control 0 no flip cnot 10 0 0 0 1 control 1 target flipped 10 11 cnot 11 0 0 1 0 control 1 target flipped 11 10 the cnot gate can create entanglement starting from 00 and applying a hadamard on qubit 0 followed by cnot produces a bell state i np eye 2 dtype complex h 1 np sqrt 2 np array 1 1 1 1 dtype complex hadamard on qubit 0 identity on qubit 1 h_i np kron h i bell state preparation cnot h x i 00 bell cnot h_i ket_00 print bell state bell 0 70710678 0 j 0 0 j 0 0 j 0 70710678 0 j this is 00 11 sqrt 2 tensor product properties one of the most useful tensor product identities is the mixed product property a x b c x d ac x bd this means applying a to qubit 0 and b to qubit 1 simultaneously is the same as computing the tensor product of the individual operations import numpy as np h 1 np sqrt 2 np array 1 1 1 1 dtype complex x np array 0 1 1 0 dtype complex z np array 1 0 0 1 dtype complex y np array 0 1 j 1 j 0 dtype complex a b h x c d z y mixed product property a x b c x d ac x bd left np kron a b np kron c d right np kron a c b d print np allclose left right true this identity is computationally important if you need to apply single qubit gates to separate qubits you can compute each single qubit product independently 2x2 multiplications and then take the tensor product rather than doing full 4x4 or larger matrix multiplications for n qubits this can mean the difference between o n and o 4 n operations hermitian matrices and observables an observable is a physical quantity you can measure in quantum mechanics observables correspond to hermitian matrices matrices equal to their own conjugate transpose the eigenvalues of a hermitian matrix are always real and they are the possible outcomes of measuring that observable import numpy as np z np array 1 0 0 1 dtype complex def is_hermitian a return np allclose a a conj t print is_hermitian z true eigenvalues of z are the measurement outcomes 1 and 1 eigenvalues eigenvectors np linalg eigh z print outcomes eigenvalues 1 1 the expectation value tells you the average measurement outcome for a state psi ket_0 np array 1 0 dtype complex ket_1 np array 0 1 dtype complex average z measurement on psi np array 1 np sqrt 2 1 np sqrt 2 dtype complex expectation np real psi conj z psi print f z expectation 3f 0 000 equal mix of 1 and 1 spectral decomposition the spectral theorem states that any hermitian matrix h can be written as h sum_i lambda_i e_i e_i where lambda_i are the eigenvalues and e_i are the corresponding eigenvectors this decomposition is central to quantum mechanics it tells you that measuring an observable h yields outcome lambda_i with probability e_i psi 2 import numpy as np z np array 1 0 0 1 dtype complex eigenvalues eigenvectors np linalg eigh z reconstruct z from its spectral decomposition z_reconstructed sum lam np outer vec vec conj for lam vec in zip eigenvalues eigenvectors t print np allclose z z_reconstructed true the spectral decomposition also works for more complex observables here is an example with the pauli x matrix whose eigenstates are and x np array 0 1 1 0 dtype complex eigenvalues eigenvectors np linalg eigh x print x eigenvalues eigenvalues 1 1 print x eigenvectors columns print eigenvectors the columns are and up to global phase measurement probabilities in the x basis psi np array 1 0 dtype complex 0 for lam vec in zip eigenvalues eigenvectors t prob abs vec conj psi 2 print f p x lam 0f prob 3f p x 1 0 500 p x 1 0 500 commutators and pauli algebra two matrices a and b commute if ab ba when two gates commute you can apply them in either order and get the same result the commutator a b ab ba measures how far two operators are from commuting if a b 0 the operators commute the pauli matrices have a beautiful algebraic structure x and z anti commute meaning xz zx import numpy as np i np eye 2 dtype complex x np array 0 1 1 0 dtype complex y np array 0 1 j 1 j 0 dtype complex z np array 1 0 0 1 dtype complex x and z anti commute xz zx print np allclose x z z x true the commutator x z xz zx 2 xz since zx xz def commutator a b return a b b a pauli commutation relations x y 2iz y z 2ix z x 2iy print np allclose commutator x y 2 j z true print np allclose commutator y z 2 j x true print np allclose commutator z x 2 j y true these commutation relations matter in several practical contexts hamiltonian simulation trotterization error depends on the commutators of the hamiltonian terms if all terms commute there is no trotter error at all quantum error correction stabilizer codes are built from commuting sets of pauli operators the check for whether an error is detectable involves commutation with these stabilizers variational algorithms the gradient of a parameterized quantum circuit involves commutators of the generators with the observable the anti commutator a b ab ba is also useful for distinct pauli matrices the anti commutator is always zero def anticommutator a b return a b b a print np allclose anticommutator x y np zeros 2 2 true print np allclose anticommutator y z np zeros 2 2 true print np allclose anticommutator z x np zeros 2 2 true density matrices so far every state we have discussed is a pure state represented by a single state vector but quantum systems can also be in mixed states which arise when there is classical uncertainty about which quantum state a system is in density matrices provide a unified framework for both pure and mixed states for a pure state psi the density matrix is the outer product rho psi psi import numpy as np ket_0 np array 1 0 dtype complex ket_1 np array 0 1 dtype complex pure state density matrix psi np array 1 np sqrt 2 1 np sqrt 2 dtype complex rho_pure np outer psi psi conj print pure state density matrix print rho_pure 0 5 0 j 0 5 0 j 0 5 0 j 0 5 0 j a mixed state represents classical uncertainty if a qubit is in state 0 with probability 0 5 and state 1 with probability 0 5 the density matrix is a weighted sum mixed state 50 0 50 1 rho_mixed 0 5 np outer ket_0 ket_0 conj 0 5 np outer ket_1 ket_1 conj print mixed state density matrix print rho_mixed 0 5 0 j 0 0 0 j 0 0 0 j 0 5 0 j notice that the mixed state and the pure state have different density matrices even though both give 50 50 measurement outcomes in the z basis the off diagonal elements called coherences distinguish them a pure superposition has nonzero coherences a classical mixture does not every valid density matrix satisfies two properties trace equal to 1 and positive semidefiniteness you can check purity with the trace of rho squared trace is 1 for both print f tr rho_pure np trace rho_pure real 3f 1 000 print f tr rho_mixed np trace rho_mixed real 3f 1 000 purity tr rho 2 1 for pure states 1 for mixed purity_pure np trace rho_pure rho_pure real purity_mixed np trace rho_mixed rho_mixed real print f purity of pure state purity_pure 3f 1 000 print f purity of mixed state purity_mixed 3f 0 500 partial trace and entanglement when two qubits are entangled neither qubit has a well defined pure state on its own the partial trace lets you compute the reduced density matrix of one qubit by tracing out the other if the result is a mixed state the two qubits are entangled import numpy as np ket_0 np array 1 0 dtype complex ket_1 np array 0 1 dtype complex ket_00 np kron ket_0 ket_0 ket_11 np kron ket_1 ket_1 bell state 00 11 sqrt 2 bell ket_00 ket_11 np sqrt 2 rho_bell np outer bell bell conj partial trace over qubit 1 to get the reduced state of qubit 0 reshape the 4x4 matrix into a 2 2 2 2 tensor then trace over qubit 1 rho_q0 rho_bell reshape 2 2 2 2 trace axis1 1 axis2 3 print reduced density matrix of qubit 0 print rho_q0 0 5 0 j 0 0 0 j 0 0 0 j 0 5 0 j this is the maximally mixed state qubit 0 has no definite state purity np trace rho_q0 rho_q0 real print f purity purity 3f 0 500 the maximally mixed reduced state confirms that the bell state is maximally entangled for a product unentangled state the partial trace would yield a pure state with purity 1 compare with a product state x 0 plus np array 1 np sqrt 2 1 np sqrt 2 dtype complex product np kron plus ket_0 rho_product np outer product product conj partial trace over qubit 1 rho_q0_product rho_product reshape 2 2 2 2 trace axis1 1 axis2 3 print reduced state of qubit 0 product state print rho_q0_product 0 5 0 j 0 5 0 j 0 5 0 j 0 5 0 j purity_product np trace rho_q0_product rho_q0_product real print f purity purity_product 3f 1 000 pure as expected common mistakes here are pitfalls that frequently trip up people who are new to quantum computing linear algebra 1 matrix multiplication order in circuit diagrams time flows left to right you draw gate u1 before gate u2 but in the matrix expression u2 goes on the left the combined operation is u2 u1 this is because the state vector sits on the right and the first operation to touch it must be the rightmost matrix import numpy as np h 1 np sqrt 2 np array 1 1 1 1 dtype complex x np array 0 1 1 0 dtype complex ket_0 np array 1 0 dtype complex circuit 0 h x means the matrix expression is x h 0 correct x h ket_0 wrong h x ket_0 this would be the circuit 0 x h print f correct h then x correct print f wrong x then h wrong print f same np allclose correct wrong false 2 forgetting the complex conjugate in inner products the inner product phi psi requires conjugating the first vector if both vectors have real entries forgetting the conjugate makes no difference but with complex amplitudes it matters import numpy as np phi np array 1 1 j dtype complex np sqrt 2 psi np array 1 1 dtype complex np sqrt 2 correct_ip phi conj psi wrong_ip phi psi missing conjugate print f correct phi psi correct_ip 0 5 0 5j print f wrong phi psi wrong_ip 0 5 0 5j 3 using real dtypes when complex numbers are needed numpy silently discards imaginary parts if you assign a complex value to a real typed array always use dtype complex for quantum state vectors import numpy as np dangerous real dtype silently drops imaginary parts bad_state np array 1 0 dtype float y np array 0 1 j 1 j 0 dtype complex result y bad_state this works but if you try to store a complex result in a float array container np zeros 2 dtype float container y np array 1 0 dtype complex would raise error safe always use complex dtype good_state np array 1 0 dtype complex result y good_state print result 0 0 j 0 1 j imaginary part preserved 4 confusing tensor product with matrix product the tensor product np kron and matrix product do very different things the tensor product combines two systems into a larger one expanding the dimension the matrix product applies an operator within the same space keeping the dimension fixed import numpy as np a np array 1 0 0 1 dtype complex z gate b np array 0 1 1 0 dtype complex x gate tensor product 2x2 x 2x2 4x4 combines two qubit spaces tensor np kron a b print f tensor product shape tensor shape 4 4 matrix product 2x2 2x2 2x2 composes operations on one qubit product a b print f matrix product shape product shape 2 2 5 confusing state norm with inner product the norm of a state vector which should be 1 is a real number the inner product of two different states is a complex number these are related but distinct operations import numpy as np psi np array 1 np sqrt 2 1 j np sqrt 2 dtype complex phi np array 1 0 dtype complex norm always real always non negative norm np sqrt psi conj psi real print f psi norm 4f 1 0000 inner product generally complex ip phi conj psi print f phi psi ip 0 7071067811865476 0j print f phi psi 2 abs ip 2 4f 0 5000 measurement probability why this matters every concept in quantum computing maps directly to linear algebra quantum states are unit vectors in complex vector spaces quantum gates are unitary matrices measurement outcomes are eigenvalues of hermitian matrices multi qubit systems are tensor products of individual qubit spaces probabilities come from squared magnitudes of inner products mixed states and decoherence are described by density matrices entanglement is detected through the partial trace gate ordering in circuits maps to matrix multiplication order reversed observable decomposition uses the pauli basis and the spectral theorem with these foundations in place you can read the mathematical notation in quantum computing papers and understand what quantum circuit simulators are actually computing under the hood next steps bra ...
|