numpy数组被四舍五入吗?减去小花车 [英] Numpy array being rounded? subtraction of small floats

查看:92
本文介绍了numpy数组被四舍五入吗?减去小花车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分配一个numpy数组的元素,使其等于减去小"值的python浮点型数字.当我这样做时,尝试通过打印到命令行来验证结果,该数组将报告为全零.这是我的代码:

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

输出看起来像这样:

-0.438765
-0.394747
[0 0 0]

我对v1期望如此:

[-0.044018 0 0]

我承认,我是numpy的新手,这可能是对numpy和float的工作方式的明显误解.我以为更改numpy打印选项会解决,但没有运气.任何帮助都很棒!谢谢!

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!

推荐答案

您要使用 v1 = np.array([0,0,0])声明数组,numpy会假设您想要一个int数组.对其执行的任何后续操作都将保持此int数组状态,因此,在明智地添加了小数元素之后,它将强制转换回int(导致全零).用

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)

numpy有很多特定于numpy或特定于平台的数据类型,有关详细信息,请参见 dtype文档页面.

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

这篇关于numpy数组被四舍五入吗?减去小花车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆