Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use Qiskit Aer to compare an ideal circuit, the same circuit with a controlled noise model, and a three-qubit repetition code that detects and corrects one bit flip. The workflow is: install pinned Qiskit packages, establish noiseless counts, encode one logical qubit into three data qubits, measure two stabilizers with ancillas, conditionally apply the identified correction, and estimate logical-error probability from repeated shots.

This tutorial uses the repetition (bit-flip) code because its syndrome logic is small enough to inspect directly. It does not demonstrate universal quantum error correction: the code corrects bit-flip errors but does not protect arbitrary phase errors or an unknown quantum state without additional code structure.

Install a reproducible Qiskit environment

Install Qiskit and Qiskit Aer in a fresh virtual environment so the simulator and circuit APIs are from a known release. The current IBM Quantum noise-model guide lists these example requirements: qiskit[all]~=2.5.2, qiskit-ibm-runtime~=0.47.0, and qiskit-aer~=0.17.0 (or newer). Those are guide examples, not a promise that every future release will behave identically. Record the versions you actually use with every experiment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
python -m venv qec-qiskit
# macOS/Linux
source qec-qiskit/bin/activate
# Windows PowerShell
# .qec-qiskitScriptsActivate.ps1
python -m pip install --upgrade pip
python -m pip install "qiskit[all]~=2.5.2" "qiskit-aer~=0.17.0"
python -c "import qiskit, qiskit_aer; print(qiskit.__version__, qiskit_aer.__version__)"

If you choose newer versions, check the installed API for dynamic-circuit conditionals and result formatting before treating the examples below as drop-in production code. Qiskit circuit and result interfaces can change between releases.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Choose an Aer simulation method

AerSimulator can select a method automatically. Start with method="automatic"; it chooses a representation compatible with the circuit and noise model. Select a method explicitly when you need predictable performance or a particular physical representation.

Method Best use Main constraint
automatic First runs and mixed experiments where Aer should choose the representation The selected method can vary with circuit and options
stabilizer Large Clifford circuits, including repetition-code experiments built only from Clifford gates and Pauli noise Cannot represent non-Clifford gates or arbitrary non-Clifford noise
statevector Pure-state circuits and noise models that can be represented by state-vector trajectories Memory grows exponentially with qubit count
density_matrix Experiments requiring an explicit mixed-state density matrix Usually becomes memory-intensive sooner than state-vector simulation
matrix_product_state Circuits whose entanglement remains suitable for tensor-network compression Performance depends strongly on entanglement and gate layout

The stabilizer method is attractive for scaling this particular code because encoding, syndrome extraction, conditional Pauli corrections, and Pauli bit-flip noise are Clifford-compatible. Use state-vector or density-matrix simulation when the circuit or channel requires it, rather than forcing a faster method that cannot faithfully represent the experiment.

Run a noiseless baseline first

A baseline tells you what counts should look like before noise, syndrome logic, or a decoder can obscure the result. Prepare a known logical |1̄⟩ state, encode it, and measure all three data qubits. For an ideal repetition code, all three data bits should agree.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

baseline = QuantumCircuit(3, 3)
baseline.x(0)                 # prepare physical qubit 0 in |1>
baseline.cx(0, 1)             # encode |1> as |111>
baseline.cx(0, 2)
baseline.measure([0, 1, 2], [0, 1, 2])

sim = AerSimulator(method="automatic")
result = sim.run(baseline, shots=4000, seed_simulator=1234).result()
ideal_counts = result.get_counts()
print(ideal_counts)

With no noise, the dominant (and normally exclusive) result is the all-one string, subject to the bit-string ordering used by the installed Qiskit version. Always inspect one returned key rather than assuming that its left-to-right order matches the order of qubit indices. A fixed simulator seed makes debugging reproducible; use a documented seed policy when comparing experiments.

What the three-qubit repetition code protects

The code maps one logical qubit into three data qubits. For the classical test states, logical zero becomes |000⟩ and logical one becomes |111⟩. If at most one data qubit suffers an X (bit-flip) error, a majority vote recovers the original logical bit.

Two stabilizers reveal which qubit disagrees with the other two:

  • S0 = Z0Z1 checks whether data qubits 0 and 1 have equal computational-basis values.
  • S1 = Z1Z2 checks whether data qubits 1 and 2 have equal values.

An ancilla initialized to |0⟩ acquires the parity of the two data qubits through two CNOTs. Measuring that ancilla gives one syndrome bit without directly measuring the logical data value. A second ancilla measures the other stabilizer.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
Error on data qubit S0 (Z0Z1) S1 (Z1Z2) Correction
None 0 0 None
X on q0 1 0 X on q0
X on q1 1 1 X on q1
X on q2 0 1 X on q2

The table assumes syndrome bit 0 stores S0 and syndrome bit 1 stores S1. When those two classical bits are interpreted as a little-endian integer, the correction values are 1 for q0, 3 for q1, and 2 for q2. Verify the mapping with a deterministic injected X before adding random noise.

Build and test a corrected circuit

Prepare and encode the logical state

Use five qubits: data qubits 0–2 and syndrome ancillas 3–4. Use a two-bit classical register for the syndrome and a one-bit register for the final logical readout. The following circuit prepares logical one and encodes it with two CNOTs.

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

q = QuantumRegister(5, "q")
syn = ClassicalRegister(2, "syn")
out = ClassicalRegister(1, "out")
qc = QuantumCircuit(q, syn, out)

qc.x(q[0])
qc.cx(q[0], q[1])
qc.cx(q[0], q[2])

Optionally inject a deterministic error

For a unit test, insert exactly one X gate after encoding. Change error_qubit to 0, 1, or 2 and confirm that the corresponding syndrome and correction are selected. Remove this gate for a stochastic-noise experiment.

error_qubit = 1
qc.x(q[error_qubit])

Measure both stabilizers

Measure S0 into syn[0] and S1 into syn[1]. The ancillas start in |0⟩, so no explicit reset is needed in this one-shot circuit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
# S0 = Z0 Z1
qc.cx(q[0], q[3])
qc.cx(q[1], q[3])
qc.measure(q[3], syn[0])

# S1 = Z1 Z2
qc.cx(q[1], q[4])
qc.cx(q[2], q[4])
qc.measure(q[4], syn[1])

Apply the syndrome-dependent correction

Qiskit 2.x supports dynamic-circuit blocks through if_test. The exact conditional syntax is version-sensitive, so check the API in the environment where you run the circuit. With the register layout above, the conditions implement the syndrome table.

with qc.if_test((syn, 1)) as else_:
    qc.x(q[0])
with else_:
    with qc.if_test((syn, 3)) as else2_:
        qc.x(q[1])
    with else2_:
        with qc.if_test((syn, 2)):
            qc.x(q[2])

If your installed release does not accept nested if_test blocks in this form, use its documented classical-condition syntax or run a lookup-table decoder after measuring the syndrome. Do not silently substitute a condition on the wrong classical register: that produces a circuit that runs but corrects the wrong qubit.

Measure the decoded logical value

After correction, measure one data qubit, conventionally q0, into the output bit.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
qc.measure(q[0], out[0])
print(qc.draw())

For the encoded logical basis states used here, every correctly corrected data qubit has the same logical value. Measuring only q0 keeps the dynamic-correction example compact. For a diagnostic experiment, measure all three data qubits after correction and apply a majority decoder; that exposes residual two-error events that a single output bit can hide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add a controlled Aer noise model

Aer noise models are explicit assumptions about where and how errors occur. The following model applies an independent Pauli channel after every single-qubit X gate and every CNOT. It is deliberately simple so that its effect can be attributed to the chosen physical error probability.

from qiskit_aer.noise import NoiseModel, pauli_error

noise = NoiseModel()
bit_flip = pauli_error([("X", 0.01), ("I", 0.99)])
noise.add_all_qubit_quantum_error(bit_flip, ["x", "cx"])

noisy_sim = AerSimulator(
    method="automatic",
    noise_model=noise
)
noisy_result = noisy_sim.run(
    qc,
    shots=4000,
    seed_simulator=1234
).result()
noisy_counts = noisy_result.get_counts()
print(noisy_counts)

The error probability in this example is 0.01 per selected gate application, not a universal property of a processor and not a logical-error rate. Changing the gate list changes the experiment. You can model other channels with Aer helpers such as depolarizing, thermal-relaxation-style, and general Pauli errors. A ReadoutError models measurement confusion and should be attached to measurements rather than gates.

Keep comparison arms identical

For a meaningful comparison, hold the following constant across circuits:

  • Shot count and simulator seed policy.
  • Logical-state preparation and final measurement.
  • Noise probabilities and the gates to which they are attached.
  • Transpilation settings, if transpilation is performed.
  • Decoder definition and the rule for counting a logical failure.

Use three experimental arms:

  1. Unencoded: prepare one qubit and measure it under the same physical noise assumptions.
  2. Encoded with correction: encode, extract the syndrome, apply the conditional correction, and decode.
  3. Repeated correction cycles: repeat syndrome extraction and correction before the final measurement to study accumulated memory and measurement costs.

A useful additional control is an encoded circuit with correction deferred until the end. The IBM repetition-code tutorial compares dynamic correction with correction deferred until final measurement; reproducing both makes it easier to separate error-correction benefit from the extra gates and measurements used to obtain the syndrome.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define and calculate logical-error probability

A logical error is a decoded result that differs from the prepared logical value. If the prepared state is logical one, count a shot as a failure when the decoder returns zero. For logical zero, count a decoded one. Do not count a wrong syndrome by itself as a logical error if the final decoded value is still correct; track syndrome statistics separately when diagnosing the circuit.

Majority decoding for a full data readout

If you measure all three data qubits into a dedicated three-bit register after correction, decode each shot by majority vote. Because Qiskit count strings may contain multiple registers and display the most significant classical bit first, parse the named register or test the bit ordering with a noiseless run before calculating rates.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
def majority(bits):
    return 1 if bits.count("1") >= 2 else 0

# Example only: supply three data bits in q0,q1,q2 order after
# converting the returned key with the register layout of your version.
logical_failures = sum(
    1 for data_bits in decoded_data_strings
    if majority(data_bits) != 1
)
logical_error_rate = logical_failures / len(decoded_data_strings)

For the compact circuit that measures only q0, the decoder is simply that output bit. Keep the compact and majority-decoded experiments as separate definitions; otherwise their logical-error rates are not directly comparable.

Report shot uncertainty

With N independent shots and an observed logical-error fraction p̂, the binomial standard error is approximately sqrt(p̂(1−p̂)/N). At very low error rates, an interval based on a binomial method such as Wilson or an exact interval is more informative than reporting zero. State the shot count, confidence method, seed policy, and whether uncertainty includes only sampling or also uncertainty in the noise parameters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sweep physical error rates and cycle counts

A single noise setting cannot show whether an apparent improvement is robust. Build a sweep in which the physical error probability changes while circuit structure, shots, and decoding remain fixed. For each probability, run the unencoded and corrected arms and store the logical-error estimate and its interval.

import numpy as np

physical_rates = np.linspace(0.0, 0.05, 11)
shots = 4000
rows = []

for p in physical_rates:
    model = NoiseModel()
    channel = pauli_error([("X", float(p)), ("I", 1.0 - float(p))])
    model.add_all_qubit_quantum_error(channel, ["x", "cx"])
    sim = AerSimulator(noise_model=model, method="automatic")
    # Run separately prepared unencoded and corrected circuits here.
    # Decode each result with the same logical-failure rule.
    rows.append({"physical_error": p, "shots": shots,
                 "logical_error": measured_rate})

For memory-style tests, add idle periods or repeated syndrome-and-correction cycles and plot logical-error probability against cycle count. Report whether an idle period is represented by an explicit delay, an identity-like gate, or simply additional circuit depth; those choices produce different noise exposure.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use device-informed noise carefully

Aer can construct an approximate noise model from reported backend calibration properties, including gate-error and relaxation parameters. This is useful for studying how selected calibration data might affect the circuit, but it is not a complete replica of hardware behavior. Calibration values change over time, and the generated model may omit correlated errors, crosstalk, leakage, drift, control errors, and effects introduced by compilation.

When using a calibration-derived model, record the backend and calibration timestamp, the gates and qubits included, the transpiler layout, basis gates, coupling map, and every approximation made during model construction. Compare it with a hand-built model so readers can distinguish conclusions that follow from the code from conclusions that depend on one calibration snapshot.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failure modes and fixes

The syndrome appears reversed

Classical-register display order is a frequent source of confusion. Inject X on q0, q1, and q2 one at a time and print the raw keys. Confirm which displayed character corresponds to syn[0] and which corresponds to syn[1] before writing the decoder.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

The conditional correction never runs

Check that the condition references the two-bit syndrome register, not the output register or a combined integer whose bit positions include the output bit. Also verify that the installed Qiskit version supports the dynamic-circuit construct used in the example.

Counts contain unexpected spaces or register separators

Multiple classical registers are rendered with separators in many Qiskit result formats. Use the circuit’s register names and a known noiseless result to map each substring. Do not infer logical values from a string position without this check.

The simulator rejects the noise model

Some methods support only particular channels. Start with method="automatic". If you select stabilizer, restrict the circuit and noise to stabilizer-compatible operations. Use state-vector or density-matrix simulation for channels or gates outside that set.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encoded results are worse than unencoded results

That outcome can be real. The code adds CNOTs, ancilla measurements, conditional operations, and more opportunities for faults. At low physical error rates, correction can help; at higher rates, extra circuit exposure can dominate. Check gate-specific noise, readout error, syndrome-measurement faults, and the decoder before claiming a coding benefit.

The experiment claims protection of an arbitrary qubit

The repetition code protects computational-basis information against a single bit flip. A phase flip acts differently, and an unknown superposition can lose coherence even when a majority vote returns the expected classical bit. Describe this as a bit-flip code or a classical-information memory experiment, not as a complete quantum memory.

How to interpret results responsibly

Every logical-error curve is conditional on a circuit, channel, placement of errors, calibration snapshot, transpilation, measurement model, decoder, and shot count. Two studies can use the same code and obtain different rates because those choices differ. Put them in the figure caption or experiment record rather than presenting one number as a universal threshold.

The repetition code only corrects bit-flip errors and therefore is not a complete error-correction code. Its value in simulation is diagnostic: it demonstrates syndrome extraction, conditional feedback, decoder design, and the cost of adding protection. Larger studies can extend the same measurement-and-decoding pattern to codes that address both bit and phase errors, but those require additional stabilizers and a substantially different resource analysis.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical checklist

  • Pin and record Qiskit and Qiskit Aer versions.
  • Run an ideal baseline before adding noise.
  • Verify syndrome-to-qubit mapping with deterministic single-X tests.
  • Use the same shots, preparation, measurements, transpilation, and seed policy in comparison arms.
  • State exactly which gates and measurements receive each error channel.
  • Choose stabilizer only when the circuit and noise are supported; otherwise use automatic, statevector, or density_matrix as appropriate.
  • Decode from named classical registers after confirming bit ordering.
  • Report logical-error uncertainty and the number of shots.
  • Label calibration-derived noise as an approximation, not a hardware replica.
  • Describe the repetition code’s bit-flip-only scope and avoid universal-memory claims.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.