简体   繁体   中英

Compare elements of 2D array to the product of two 1D arrays?

I'm trying to compare a 2D array to the product of two 1D arrays (joint-probability density vs product of its individual probability densities) in order to determine if variables x and y are independent, where independence is given as ρ(x,y)=ρ(x)*ρ(y) .

Let's say I called the 2D array h , and the 1D lists n and m . How would I go about iterating over h to check if it's elements are equivalent to n*m ?

To test for exact equality, just use np.all()

import numpy as np

m = np.random.rand(10)
n = np.random.rand(20)
h = m.reshape(1, -1) * n.reshape(-1, 1)

print(np.all(h == m.reshape(1, -1) * n.reshape(-1, 1))) # True

To test whether the numbers are all close, you could use:

print(np.all(np.isclose(h, m.reshape(1, -1) * n.reshape(-1, 1))))

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