简体   繁体   English

Numpy vs Python浮点计算产生不同的结果

[英]Numpy vs Python floating point calculations produce different results

I have a list of lists of floats, like this: 我有一个浮动列表的列表,像这样:

u = [[1.2, 1.534, 23.5, ...], [0.2, 11.5, 3.3223, ...], ...]

Using Python to calculate a new list (height and width are the lists dimensions, u2 is a list of lists of floats set to 0.0): 使用Python计算新列表(高度和宽度是列表尺寸,u2是设置为0.0的浮点列表的列表):

for time in xrange(start, stop):
    for i in xrange(1,height-1):
        for j in xrange(1, width-1):
            u2[i][j] = u[i][j-1] + u[i-1][j] - time * (u[i][j+1] / u[i+1][j])
    u = deepcopy(u2)

As expected, this produces a new list of lists of floats. 如预期的那样,这将产生一个新的浮点列表列表。

However, transferring this to Numpy, with a simple: 但是,使用以下简单方法将其转移到Numpy:

un = array(u)

Then using the same kind of loop (u2 being an array of zeroes this time): 然后使用相同类型的循环(这次u2是零数组):

for time in xrange(start, stop):
    for i in xrange(1,height-1):
        for j in xrange(1, width-1):
            u2[i][j] = un[i][j-1] + un[i-1][j] - time * (un[i][j+1] / un[i+1][j])
    un = u2

... produces equal results as the Python implementation as long as height , width and the timerange are all small, but differing results as these variables are set higher and higher. 只要高度宽度和时间范围都很小,...就会产生与Python实现相同的结果,但是随着这些变量的设置越来越高,结果会有所不同。

  • Is there a way to prevent this build-up of float-inaccuracy? 有没有办法防止这种浮点误差的积累?

(This is not real code, just me fiddling around to understand how numbers are treated in Python and Numpy, so any suggestions regarding vectorization or other Numpy-efficiency stuff is off-topic) (这不是真正的代码,只是我想弄清楚如何在Python和Numpy中处理数字,因此有关向量化或其他Numpy效率的内容的任何建议都是题外话)

At first glance the problem seems to be un = u2 . 乍一看,这个问题似乎是un = u2 This creates a reference to u2 rather than a copy, so you are directly modifying u inside your inner loop. 这将创建对u2的引用,而不是副本,因此您可以直接在内部循环中修改u This will give you different results to the pure Python version since the value at u2[i][j] depends on u[i][j-1] and u[i-1][j] . 这将给您与纯Python版本不同的结果,因为u2[i][j]取决于u[i][j-1]u[i-1][j]

Try un = u2.copy() to force a copy instead. 尝试使用un = u2.copy()强制复制。

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

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