numpy.bitwise_and.reduce يتصرف بشكل غير متوقع؟
-
22-12-2019 - |
سؤال
ال ufunc.reduce
لأن numpy.bitwise_and.reduce لا يبدو أنه يتصرف بشكل صحيح...هل أنا أسيء استخدامه؟
>>> import numpy as np
>>> x = [0x211f,0x1013,0x1111]
>>> np.bitwise_or.accumulate(x)
array([ 8479, 12575, 12575])
>>> np.bitwise_and.accumulate(x)
array([8479, 19, 17])
>>> '%04x' % np.bitwise_or.reduce(x)
'311f'
>>> '%04x' % np.bitwise_and.reduce(x)
'0001'
نتائج reduce()
يجب أن تكون القيمة الأخيرة لـ accumulate()
وهذا ليس كذلك.ما الذي أفتقده هنا؟
في الوقت الحالي، يمكنني حل المشكلة باستخدام هوية DeMorgan (مبادلة OR وAND، وعكس الإدخال والإخراج):
>>> ~np.bitwise_or.reduce(np.invert(x))
17
المحلول
وفقا للوثائق التي قدمتها، ufunc.reduce
الاستخدامات op.identity
كقيمة أولية.
numpy.bitwise_and.identity
يكون 1
, ، لا 0xffffffff....
ولا -1
.
>>> np.bitwise_and.identity
1
لذا numpy.bitwise_and.reduce([0x211f,0x1013,0x1111])
يعادل:
>>> np.bitwise_and(np.bitwise_and(np.bitwise_and(1, 0x211f), 0x1013), 0x1111)
1
>>> 1 & 0x211f & 0x1013 & 0x1111
1
>>> -1 & 0x211f & 0x1013 & 0x1111
17
يبدو أنه لا توجد طريقة لتحديد القيمة الأولية وفقًا للوثائق.(على عكس وظيفة بايثون المضمنة reduce
)
لا تنتمي إلى StackOverflow