简体   繁体   English

使用嵌套的for循环在每个坐标处评估函数-python

[英]Using nested for loops to evaluate function at every coordinate - python

I am trying to use a nested for loop to evaluate function f(r) at every combination of 2D polar coordinates. 我正在尝试使用嵌套的for循环在二维极坐标的每个组合处评估函数f(r)。

My current code is: 我当前的代码是:

r = np.linspace(0, 5, 10)
phi = np.linespace(0,2*np.pi, 10)

for i in r:
 for j in phi:
    X = f(r) * np.cos(phi)

print X

When I run this as is it returns X as a 1D array of f(r) and cos(phi) is 1 (ie. phi = 0). 当我按原样运行时,它将返回X作为f(r)的一维数组,而cos(phi)为1(即phi = 0)。 However I want f(r) at every value of r, which is then multiplied by its corresponding phi value. 但是我想要在r的每个值处都具有f(r),然后将其乘以其对应的phi值。 This would be a 2D array (10 by 10) where by every combination of r and phi is evaluated. 这将是一个2D数组(10 x 10),其中r和phi的每种组合都会被评估。

If you have any suggestions about possible efficiencies I would appreciate it as eventually I will be running this with a resolution much greater than 10 (maybe as high as 10,000) and looping it many thousands of times. 如果您对可能的效率有任何建议,我将不胜感激,因为最终我将以大于10的分辨率(可能高达10,000)运行此分辨率,并使其循环数千次。

  1. It's np.linspace not np.linespace . 它是np.linspace而不是np.linespace
  2. You're not iterating over the actual data at all, ie i and j are not even used in your inner loop. 您根本不需要遍历实际数据,即, ij甚至不在您的内部循环中使用。 Right now, you're executing the same statement with the same arguments and the same result over and over again. 现在,您一次又一次地执行具有相同参数和相同结果的相同语句。 You could have executed the inner statement only one single time, X would be the same. 您一次只能执行一次内部语句, X相同。
  3. You need to preallocate a 2D-array for the result. 您需要为结果预分配2D数组。
  4. Iterate over both axes, grab the items of r and phi , do your calculation and put it into the right field of your output array. 遍历两个轴,获取rphi的项,进行计算并将其放入输出数组的正确字段中。
  5. Somehow the first point makes me think you never event tried to run your code, as it gives an obvious error message. 不知何故,第一点使我认为您从不尝试运行代码,因为它给出了明显的错误消息。 Anyways, here some solution: 无论如何,这里有一些解决方案:

def f(x):
    return x

r = np.linspace(0, 5, 10)
phi = np.linspace(0, 2*np.pi, 10)
X = np.zeros((len(r), len(phi)))

for i in xrange(len(r)):
    for j in xrange(len(phi)):
        X[i,j] = f(r[i]) * np.cos(phi[j])

print X

PS Don't go with the solutions, that put the results into ordinary lists, stick with numpy arrays for mathematical problems. PS不要采用将结果放入普通列表的解决方案,而应使用numpy数组处理数学问题。

When I run this as is it returns X as a 1D array of f(r) and cos(phi) is 1 (ie. phi = 0). 当我按原样运行时,它将返回X作为f(r)的一维数组,而cos(phi)为1(即phi = 0)。

That's because you don't store, print, or do anything else with all those intermediate values you generate. 那是因为您不会使用生成的所有这些中间值来存储,打印或做任何其他事情。 All you do is rebind X to the latest value over and over (forgetting whatever used to be in X ), so at the end, it's bound to the last one. 您要做的就是一遍又一遍地将X重新绑定到最新值(忘记了X曾经使用的内容),因此最后将它绑定到最后一个值。

If you want all of those X values, you have to actually store them in some way. 如果要所有这些X值,则必须以某种方式实际存储它们。 For example: 例如:

Xs = []
for i in r:
    for j in phi:
        X = f(r) * np.cos(phi)
        Xs.append[X]

Now, you'll have a list of each X instead of just the last one. 现在,您将拥有每个X的列表,而不仅仅是最后一个。

Of course in general, the whole reason you use NumPy is to "vectorize" operations instead of looping in the first place. 当然,通常,使用NumPy的全部原因是对操作进行“向量化”,而不是首先进行循环。 (This allows the loops and the arithmetic to be done in C/C++/Fortran/whatever instead of Python, typically making them an order of magnitude or so faster.) So, if you can rewrite your code to create a 2D array from your 1D array by broadcasting, instead of creating a list of 1D arrays, it will be better… (这使得循环和算术运算可以在C / C ++ / Fortran /而不是Python中完成,而通常使它们快一个数量级左右。)因此,如果您可以重写代码以从自己的代码创建2D数组通过广播一维数组,而不是创建一维数组列表,效果会更好……

Instead of assigning to X, you should be adding the most recent 1D array to it. 您应该向其添加最新的一维数组,而不是分配给X。 (You'll need to initialize X before the outer loop.) (您需要在外部循环之前初始化X。)

Edit: You don't need the inner loop; 编辑:您不需要内部循环; it's computing across all of phi (which is why you get the 1D array) repeatedly. 它在所有phi中进行计算(这就是为什么要获得一维数组的原因)。 (Note how it doesn't use j). (请注意,它如何不使用j)。 That'll speed things up a bit, AND get you the correct answer! 这样可以加快速度,并为您提供正确的答案!

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

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