For example, if $a$ is a row vector, $b$ is a column vector, how to use Q# to calculate the inner product of these two? Which method or operator can be used? Just $a*b$? Any others? Really need your help. Thank you very much.


2 Answers 2


Q# doesn't have data types to represent row or column vectors, so they'd be represented as just arrays.

You can write a straightforward for loop to iterate through the vectors and accumulate the products of elements $\sum_{i=0}^{n-1}a_ib_i$:

mutable prod = 0;
for i in 0 .. Length(a) - 1 {
    set prod += a[i] * b[i];

Alternatively, you can calculate their inner product using library functions:

  1. Zip the arrays a and b together so that they become an array of tuples: Zipped(a, b).
  2. Do pairwise multiplication for each tuple in the result: Mapped(TimesI, Zipped(a, b)).
  3. Add up pairwise products: Fold(PlusI, 0, Mapped(TimesI, Zipped(a, b))).

With the next release you'll also be able to combine the last two steps in one using lambda expressions: Fold((sum, (ai, bi)) -> sum + ai * bi, 0, Zipped(a, b)).

  • $\begingroup$ Thank you! Really appreciate your answer. And I also wonder if there exist any library functions of Q# to calculate the inner product of two qubits? for example, how to calculate the inner product of |a> and |b>? $\endgroup$
    – W.xueshan
    Commented Mar 28, 2022 at 5:00
  • $\begingroup$ Q# doesn't give you direct access to the quantum state, since it's a non-physical tool, so there is no library to do that $\endgroup$ Commented Mar 28, 2022 at 17:21
  • $\begingroup$ Got it. I am just a beginner of Q#, I got a lot of problems when I learn it by myself. You really help me a lot. Thank you for answering the question. $\endgroup$
    – W.xueshan
    Commented Mar 29, 2022 at 1:27

The inner product of two vector (of equal length, of course), is simply given by the sum of the products of the coordinates with same index.

In general, if you have two vectors a and b, then the inner product u⋅v is given by ∑a⋅b.

This is the only way I know, hope it helps.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.