#7 Circom: Comparator Circuits

This article will serve as walkthrough of common circuits found within Circomlib (primarily in comparators.circom).

  1. Num2Bits

  2. IsZero

  3. IsEqual

  4. ForceEqualIfEnabled

  5. Num2Bits [symbolic variables covered here]

  6. LessThan

  7. LessEqThan

  8. GreatThan

  9. GreaterEqThan

While Num2Bits is not found within comparators.circom, it assists with understanding some of the comparator circuits that follow it, hence covered within this chapter.

IsZero

This circuit returns 1, if in is zero. If in is non-zero, it returns 0.

template IsZero() {
		// inputs
    signal input in;
    signal output out;

		// intermediate
    signal inv;
		
    inv <-- in!=0 ? 1/in : 0;

    out <== -in*inv +1;
    in*out === 0;
}

Inputs

The circuit takes in two input signals: in and out

Intermediate signal: inv <-- in != 0 ? 1/in : 0

If the input signal in is non-zero, the intermediate signal inv, is assigned the inverse of in (1/in). Else, it takes the value 0.

  • 1/in returns the multiplicative inverse of in.

  • in * inv = 1

If input is non-zero, calc the multiplicative inverse, and assign it to inv.

Else, assign inv to be 0.

out

out is then assigned & constrained to be

  • if inv: non-zero → out = 0 | -in*inv +1 = -1 + 1 = 0

  • If inv: 0 → out = 1 | (-in * 0) + 1 = 1

If in = 0, inv = 0

-in*inv +1 = 0*0 + 1 = 1
    out = 1
    out === 1

in * out = 0 * 1 = 0  
(honouring: in*out === 0)

Therefore, if in = 0, out returns 1.

If in = 1, inv = 1/1 = 1

-in*inv +1 = -1 + 1 = 0
    out = 0
    out === 0
    
in * out = 1 * 0 = 0  
(honouring: in*out === 0)

Therefore, if in = 1, out returns 0. This applies to any non-zero value of in.

Last updated

Was this helpful?