Home > OS >  Get different result applying np.sum(np.abs(X)) and np.sum(np.real(X))
Get different result applying np.sum(np.abs(X)) and np.sum(np.real(X))

Time:08-19

Here is my code

arr2D_x0 = np.real(np.fft.ifft2(arr2D_g, norm='ortho'))
print('arr2D_x0',np.sum(np.abs(arr2D_x0)), np.sum(np.real(arr2D_x0)), np.sum(arr2D_x0), np.unique(np.imag(arr2D_x0)))
print((np.abs(arr2D_x0) == np.real(arr2D_x0)).all(), (arr2D_x0 == np.real(arr2D_x0)).all(), (np.abs(arr2D_x0) == arr2D_x0).all())

And I got the following output

arr2D_x0 16241240.101077307 13039017.97206586 13039017.97206586 [0.]
False True False

I confirmed that np.abs by (a^2 b^2)^0.5, then how can the abs and real result be different for a real array? And the difference is so big that can not be ignored. I changed arr2D_x0's data type to np.float64 and np.float96 but nothing changes in the result.

CodePudding user response:

how can the abs and real result be different for a real array?

Because they do different things.
np.abs calculates the absolute value element-wise, while np.real returns the real part of the complex argument, element-wise.

To better understand why they differ, let's assume that arr2D_x0 = np.real(np.fft.ifft2(arr2D_g, norm='ortho')) is an simple array like this one arr2D_x0 = np.array([-1.2, 1.2])

Calculating the real part of an array of real values does nothing to it; on the other hand, calculating the absolute value will turn negative values into positive. So this is basically what you are doing and the reason of different results.

x = np.real(arr2D_x0) # array([-1.2,  1.2])
np.sum(x) # 0.0

y = np.abs(arr2D_x0)  # array([1.2, 1.2])
np.sum(y) # 2.4
  • Related