Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python issues converting an numpy array from float64 to int

I encountered an odd situation in Python (version 3.9.8) and numpy (version 1.20.0)trying to convert float64 numbers to int. It started with calculating the fft coefficients with numpy and then using inverse DFT with

x = np.array([1, -4, 2, 2, 1, -4, 6, 2]) # test vector
X = np.fft.fft(x)                        # calc fft coefficients

The result is fine so far:

print(X)
[ 6. +0.j  0. +4.j -6.+12.j  0. -4.j 14. +0.j  0. +4.j -6.-12.j  0. -4.j]

Now I’ve written my own inverse DFT and get correct results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

N = len(X)       # number of samples N
y = np.zeros(N)  # create empty result vector with N elements

# calc inverse DFT
for n in np.arange(N):
    
    sum = 0
    
    for k in np.arange(N):
        sum = sum + X[k] * np.exp(1j * 2* np.pi * k * n/N)
        
    y[n] = sum.real/N

# print results
print(y)
[ 1. -4.  2.  2.  1. -4.  6.  2.]

The resulting vector is also fine.

But when I convert this vector to int strange things happen. IIn the second half of the vector, values change in ways that are inexplicable to me.

print(y.astype('int'))

[ 1 -4  2  2  0 -3  6  1]

Any idea?

>Solution :

astype(int) will truncate values to integers: it just ditches the part after the decimal period. And the floating point values you see on your screen, are rounded representations: 2. is probably something like 1.99999999 because of floating point imprecisions.

First, round the values, then convert them to integer:

np.round(y)

produces

array([ 1., -4.,  2.,  2.,  1., -4.,  6.,  2.])

which are still floating point values, but now rounded to integer values (note that all (machine-range) integers can be represented exactly by floating point numbers).

Thus do the following:

np.round(y).astype(int)

to get

array([ 1, -4,  2,  2,  1, -4,  6,  2])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading