基本的Numpy数组值分配 [英] Basic Numpy array value assignment

查看:82
本文介绍了基本的Numpy数组值分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个小练习,我开始尝试使用python中的数字代码之前,我正在尝试制作LDLT算法.只是为了弄湿脚".

As a small exercise before i start playing with numeric code in python I am trying to make an LDLT algorithm. Just to "get the feet wet".

但是我似乎对numpy数组缺乏基本的了解.请参见以下示例:

However I seem to be lacking a fundamental understanding of the numpy array. See the following example:

def ldlt(Matrix):
    import numpy

    (NRow, NCol) = Matrix.shape

    for col in range(NCol):
        Tmp = 1/Matrix[col,col]
        for D in range(col+1, NCol):
            Matrix[col,D] = Matrix[D,col]*Tmp  

if __name__ == '__main__':
    import numpy
    A = numpy.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
    ldlt(A)

该示例不是我正在处理的完整代码.但是,请尝试运行它,并在Matrix [col,D] = ...

The example is not the full code I am working on. However, try and run it, and set a break-point at Matrix[col,D] = ...

我希望第一次评估是将第0行第1列(起始值为-1)设置为= -1 *(1/2)= -0.5.

What I expect for the first evaluation is that row 0 column 1 (starting value of -1) to be set equal to = -1*(1/2) = -0.5.

但是在运行代码时,它似乎设置为等于0.为什么? 一定有一些我不太了解的基本知识吗?

However when running the code it seems to be set equal to 0. Why ? There must be something fundamental which I have not really understood?

在此先感谢所有帮助我的人.

Thanks in advance for all of you guys helping me out.

Python版本:3.3 Tmp .:变成0.5(据我的调试器报告).

Python Ver.: 3.3 Tmp.: become 0.5 (As reported by my debugger).

推荐答案

以下内容可能显示发生了什么情况:

The following may show what's going on:

>>> A = np.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
>>> A.dtype
dtype('int32')
>>> A[0, 1]
-1
>>> A[0, 1] * 0.5
-0.5
>>> A[0, 1] *= 0.5
>>> A[0, 1]
0
>>> int(-0.5)
0

您的数组只能容纳32位整数,因此您尝试分配给它的任何浮点值都将被强制转换为int32,即被截断.

Your array can only hold 32-bit integers, so any floating point value you try to assign to it will be cast, i.e. truncated, to an int32.

对于相同的价格,这是一种更加numpythonic的方式来处理您要执行的操作:for循环通常应避免,因为它们破坏了numpy的全部目的:

For the same price, here's a more numpythonic way of doing what you were after: for loops are generally to be avoided, as they defeat the whole purpose of numpy:

def ldlt_np(arr) :
    rows, cols = arr.shape
    tmp = 1 / np.diag(arr) # this is a float array
    mask = np.tril_indices(cols)
    ret = arr * tmp[:, None] # this will also be a float array
    ret[mask] = arr[mask]

    return ret

>>> A = np.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
>>> ldlt_np(A)
array([[ 2. , -0.5,  0. ],
       [-1. ,  2. , -0.5],
       [ 0. , -1. ,  2. ]])

这篇关于基本的Numpy数组值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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