I am trying to get the same result when I apply say some function product function prod(x) to x and shuffle(x) where x is some arbitrary array of integers say up to length 100, prod(x) is an function that returns the product of the entries of x, and shuffle is a function that returns x, shuffled.
ie
I want prod(x) == prod(shuffle(x)) to be True
Any help would be much appreciated. Here is a more tangible question how can I get True below?
import numpy as np
x = np.random.randint(100, 1000, 10)
x = np.asarray(x, dtype=np.float64)
xs = np.copy(x)
np.random.shuffle(xs)
y = np.prod(x)
ys = np.prod(xs)
print(y)
print(ys)
print(ys == y)
Since you have precision problem, why don't you use np.close
to check within a tolerance rather than exact equality:
#replace (ys == y) with:
np.isclose(ys, y, rtol=1e-15, equal_nan=True)
rtol=1e-10
is relative tolerance (you can set it to your desired relative error, I recommend to set it to 15 or less (around 6 bytes=48 bits, I think float64 uses 52 bits for mantissa but I am not sure)). You can use atol
argument for absolute tolerance instead of relative tolerance. equal_nan=True
considers NaN
s as equal (Set to False
it you want nan
s to be considered not equal).
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.