binary_encoding(v: Hashable, upper_bound: int) dimod.binary.binary_quadratic_model.BinaryQuadraticModel[source]

Return a binary quadratic model encoding an integer.

  • v – The integer variable label.

  • upper_bound – The upper bound on the integer value (inclusive).


A binary quadratic model. The variables in the BQM will be labelled with tuples of length two or three. The first value of the tuple will be the variable label v provided. The second value will be the coefficient in the integer encoding. One of the variables will have a third value in the tuple, 'msb'. This is the variable occupying the position of the most significant bit. Though it may actually be a smaller number in order to enforce the upper_bound.


>>> bqm = dimod.generators.binary_encoding('i', 6)
>>> bqm
BinaryQuadraticModel({('i', 1): 1.0, ('i', 2): 2.0, ('i', 3, 'msb'): 3.0}, {}, 0.0, 'BINARY')

We can use a sample to restore the original integer value.

>>> sample = {('i', 1): 1, ('i', 2): 0, ('i', 3, 'msb'): 1}
>>> bqm.energy(sample)
>>> sum(v[1]*val for v, val in sample.items()) + bqm.offset

If you wish to encode integers with a lower bound, you can use the binary quadratic model’s offset attribute.

>>> i = dimod.generators.binary_encoding('i', 10) + 5  # integer in [5, 15]


[1]: Sahar Karimi, Pooya Ronagh (2017), Practical Integer-to-Binary Mapping for Quantum Annealers. arxiv.org:1706.01945.