Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy array being rounded? subtraction of small floats

I am assigning the elements of a numpy array to be equal to the subtraction of "small" valued, python float-type numbers. When I do this, and try to verify the results by printing to the command line, the array is reported as all zeros. Here is my code:

import numpy as np
np.set_printoptions(precision=20)

pc1x = float(-0.438765)
pc2x = float(-0.394747)

v1 = np.array([0,0,0]) 

v1[0] = pc1x-pc2x

print pc1x
print pc2x
print v1

The output looks like this:

-0.438765
-0.394747
[0 0 0]

I expected this for v1:

[-0.044018 0 0]

I am new to numpy, I admit, this may be an obvious mis-understanding of how numpy and float work. I thought that changing the numpy print options would fix, but no luck. Any help is great! Thanks!

like image 886
willpower2727 Avatar asked Jan 20 '26 16:01

willpower2727


1 Answers

You're declaring the array with v1 = np.array([0,0,0]), which numpy assumes you want an int array for. Any subsequent actions on it will maintain this int array status, so after adding your small number element wise, it casts back to int (resulting in all zeros). Declare it with

v1 = np.array([0,0,0],dtype=float)

There's a whole wealth of numpy specific/platform specific datatypes for numpy that are detailed in the dtype docs page.

like image 120
csunday95 Avatar answered Jan 23 '26 05:01

csunday95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!