简体   繁体   中英

Why array have different value than anticipated?

I changed attributes of a class from:

self.firstBase = np.array([1, 0])
self.secondBase = np.array([0, 1])

to

self.base = np.array([[1, 0], [0, 1]])

Since then operation of multiplying these two vectors by Hadamard matrix returns wrong value.

def H(self):
    H = np.array([[1 / math.sqrt(2), 1 / math.sqrt(2)],
                  [1 / math.sqrt(2), - 1 / math.sqrt(2)]])

    topValue = H[0][0] * self.base[0][0] + H[0][1] * self.base[0][1]
    bottomValue = H[1][0] * self.base[0][0] + H[1][1] * self.base[0][1]
    self.base[0] = np.array([topValue, bottomValue])

    topValue = H[0][0] * self.base[1][0] + H[0][1] * self.base[1][1]
    bottomValue = H[1][0] * self.base[1][0] + H[1][1] * self.base[1][1]
    self.base[1] = np.array([topValue, bottomValue])

    return self

I did some testing and find out that calculations are still correct but when I initialize

 self.base[0] = np.array([topValue, bottomValue])

and

self.base[1] = np.array([topValue, bottomValue])

it gives me [0, 0] and [0, 0] as a result.

Why is that? What is the fix?

Change self.base datatype to float

self.base = np.array([[1, 0], [0, 1]], dtype=float)

This is happening because you are trying to assign float values to an integer array. Hence, need to initialize self.base using float values instead as follows:

  1. use self.base = np.array([1.0, 0.0], [0.0, 1.0])
  2. or self.base = np.array([[1, 0], [0, 1]], dtype=float)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM