python矩阵输出小数,numpy数组中多余的小数?

Let's say I have one list of floats and a numpy array that I wish to zip:

>>> import numpy as np

>>> n1 = [0.9, 1.1]

>>> n2 = np.array([0.9,1.1])

>>> zip(n1,n2)

[(0.9, 0.90000000000000002), (1.1, 1.1000000000000001)]

Why am I getting all those decimals? Is there a way to make the numpy floats behave like python floats?

EDIT:

It seems that calculations are also affected by the way numpy stores floats:

>>> nb1 = n2[1]+0.1

>>> nb1

1.2000000000000002

>>> nb2 = nb1 - 1.2 #nb2 should be equal to 0

2.2204460492503131e-16

>>> nb3 = np.asscalar(nb2)

>>> nb3

2.2204460492503131e-16 #nb3 should be equal to 0

>>> type(nb3)

float

解决方案

Both the python floats and the numpy arrays are probably 64-bit floating point numbers, but they are 'encapsulated' in different objects. The difference is probably due to different repr for python floats and numpy floats.

In [12]: n1[0]

Out[12]: 0.9

In [13]: n2[0]

Out[13]: 0.90000000000000002

In [14]: n1[0] == n2[0]

Out[14]: True

In [15]: type(n1[0])

Out[15]: float

In [16]: type(n2[0])

Out[16]: numpy.float64

The same problem probably triggered a previous question. Personally, I consider this a bug in numpy.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值