Comparators¶
The following comparators are supported:
- Equal (denoted as '==')
- NotEqual (denoted as '!=')
- GreaterThan (denoted as '>')
- GreaterEqual (denoted as '>=')
- LessThan (denoted as '<')
- LessEqual (denoted as '<=')
Note that integer and fixed-point numbers are represented in a 2-complement method during function evaluation. The binary number is extended in the case of a register size miss-match. For example, the positive signed number $(110)_2=6$ is expressed as $(00110)_2$ when operating with a 5-qubit register. Similarly, the negative signed number $(110)_2=-2$ is expressed as $(11110)_2$.
Examples:
(5 <= 3) = 0
(5 == 5) = 1
($(011)_2$ == $(11)_2$) = 1
(signed $(101)_2$ < unsigned $(101)_2$) = 1
In [1]:
Copied!
from classiq import Output, QArray, QBit, QNum, allocate_num, create_model, qfunc
@qfunc
def main(a: Output[QNum], b: Output[QNum], res: Output[QNum]) -> None:
allocate_num(5, True, 0, a)
allocate_num(3, False, 0, b)
res |= a == b
qmod = create_model(main)
from classiq import Output, QArray, QBit, QNum, allocate_num, create_model, qfunc
@qfunc
def main(a: Output[QNum], b: Output[QNum], res: Output[QNum]) -> None:
allocate_num(5, True, 0, a)
allocate_num(3, False, 0, b)
res |= a == b
qmod = create_model(main)
In [2]:
Copied!
from classiq import execute, synthesize, write_qmod
write_qmod(qmod, "comparator_2vars_example")
qprog = synthesize(qmod)
from classiq import execute, synthesize, write_qmod
write_qmod(qmod, "comparator_2vars_example")
qprog = synthesize(qmod)
Example 2: Comparing Integer and Quantum Variable¶
This example generates a quantum program that performs 'less equal' between a quantum register and an integer. The left arg is an unsigned quantum variable with 3 qubits, and the right arg is an integer equal to 2.
In [3]:
Copied!
from classiq import (
Output,
QArray,
QBit,
QNum,
allocate,
create_model,
hadamard_transform,
qfunc,
)
@qfunc
def main(a: Output[QNum], res: Output[QNum]) -> None:
allocate(3, a)
hadamard_transform(a)
res |= a <= 2
qmod = create_model(main)
from classiq import (
Output,
QArray,
QBit,
QNum,
allocate,
create_model,
hadamard_transform,
qfunc,
)
@qfunc
def main(a: Output[QNum], res: Output[QNum]) -> None:
allocate(3, a)
hadamard_transform(a)
res |= a <= 2
qmod = create_model(main)
In [4]:
Copied!
from classiq import execute, synthesize, write_qmod
write_qmod(qmod, "comparator_integer_example")
qprog = synthesize(qmod)
result = execute(qprog).result()[0].value
result.parsed_counts
from classiq import execute, synthesize, write_qmod
write_qmod(qmod, "comparator_integer_example")
qprog = synthesize(qmod)
result = execute(qprog).result()[0].value
result.parsed_counts
Out[4]:
[{'a': 7.0, 'res': 0.0}: 141, {'a': 5.0, 'res': 0.0}: 135, {'a': 0.0, 'res': 1.0}: 131, {'a': 2.0, 'res': 1.0}: 126, {'a': 4.0, 'res': 0.0}: 125, {'a': 3.0, 'res': 0.0}: 118, {'a': 1.0, 'res': 1.0}: 112, {'a': 6.0, 'res': 0.0}: 112]