简体   繁体   English

numpy数组被舍入? 减去小花车

[英]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. 我将numpy数组的元素分配为等于“小”值的python浮点型数字的减法。 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: 我对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. 我承认,我是numpy的新手,这可能是对numpy和float的工作方式的明显误解。 I thought that changing the numpy print options would fix, but no luck. 我以为更改numpy打印选项可以解决,但没有运气。 Any help is great! 任何帮助都很棒! Thanks! 谢谢!

You're declaring the array with v1 = np.array([0,0,0]) , which numpy assumes you want an int array for. 您正在使用v1 = np.array([0,0,0])声明数组,该numpy假定您要使用int数组。 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). 对其进行的任何后续操作都将保持此int数组状态,因此,在明智地添加了小数元素之后,它将强制转换回int(结果为全零)。 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. dtype docs页面中详细介绍了用于numpy的大量numpy特定/平台特定的数据类型

You are creating the array with an integer datatype (since you don't specify it, NumPy uses the type of the initial data you gave it). 您正在使用整数数据类型创建数组(由于未指定数组,因此NumPy使用您提供的初始数据的类型)。 Make it a float: 使其浮动:

>>> v1 = np.array([0,0,0], dtype=np.float)
>>> v1[0] = pc1x-pc2x
>>> print v1
[-0.04401800000000000157  0.                      0.                    ]

Or change the incoming datatype: 或更改传入的数据类型:

>>> v1 = np.array([0.0, 0.0, 0.0])
>>> v1[0] = pc1x-pc2x
>>> print v1
[-0.04401800000000000157  0.                      0.                    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM