使用每个先前值作为输入的numpy数组fromfunction,初始值非零 [英] numpy array fromfunction using each previous value as input, with non-zero initial value

查看:86
本文介绍了使用每个先前值作为输入的numpy数组fromfunction,初始值非零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个函数用值填充一个numpy数组。我希望数组以一个初始值开始并填充为给定的长度,使用数组中的每个先前值作为函数的输入。

I would like to fill a numpy array with values using a function. I want the array to start with one initial value and be filled to a given length, using each previous value in the array as the input to the function.

每个数组值我应该是(i-1)* x **(y / z)。

Each array value i should be (i-1)*x**(y/z).

经过一些工作,我必须:

After a bit of work, I have got to:

import numpy as np
f = np.zeros([31,1])
f[0] = 20
fun = lambda i, j: i*2**(1/3)
f[1:] = np.fromfunction(np.vectorize(fun), (len(f)-1,1), dtype = int)

这将用

[firstvalue = 20,0,i-1 + 1 * 2 **(1/3),...]

[firstvalue=20, 0, i-1 + 1*2**(1/3),...]

我已经读过这里了

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfunction.html

< a href = https://stackoverflow.com/questions/40672367/use-of-numpy-fromfunction>使用numpy fromfunction

在numpy数组上映射函数的最有效方法

Fastest way to populate a matrix with a function on pairs of elements in two numpy vectors?

如何创建numpy

但是我只是不知道如何将其转换为函数。

But I'm just not getting how to translate it to my function.

推荐答案

除了前20个之外,这将产生相同的值

Except for the initial 20, this produces the same values

np.arange(31)*2**(1/3)






您的迭代版本(稍作修改)


Your iterative version (slightly modified)

def foo0(n):
    f = np.zeros(n)
    f[0] = 20
    for i in range(1,n): 
        f[i] = f[i-1]*2**(1/3)
    return f

另一种方法:

def foo1(n):
    g = [20]
    for i in range(n-1):
        g.append(g[-1]*2**(1/3))
    return np.array(g)

它们产生相同的结果:

In [25]: np.allclose(foo0(31), foo1(31))
Out[25]: True

矿山速度更快:

In [26]: timeit foo0(100)
35 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [27]: timeit foo1(100)
23.6 µs ± 83.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

但是我们不需要评估 2 **(1/3)每次

But we don't need to evaluate 2**(1/3) every time

def foo2(n):
    g = [20]
    const = 2**(1/3)
    for i in range(n-1):
        g.append(g[-1]*const)
    return np.array(g)

次要时间节省。但这只是将每个条目乘以相同的const。因此我们可以使用 cumprod 节省更多时间:

minor time savings. But that's just multiplying each entry by the same const. So we can use cumprod for a bigger time savings:

def foo3(n):
    g = np.ones(n)*(2**(1/3))
    g[0]=20
    return np.cumprod(g)

In [37]: timeit foo3(31)
14.9 µs ± 14.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [40]: np.allclose(foo0(31), foo3(31))
Out[40]: True

这篇关于使用每个先前值作为输入的numpy数组fromfunction,初始值非零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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