[英]Javascript to Python with bitwise shift in a for loop's condition and final-expression
I have a FFT code written in javascript, pasted below: 我有一个用JavaScript编写的FFT代码,粘贴如下:
function FFT(re, im) {
var N = re.length;
for (var i = 0; i < N; i++) {
for (var j = 0, h = i, k = N; k >>= 1; h >>= 1)
j = (j << 1) | (h & 1);
if (j > i) {
re[j] = [re[i], re[i] = re[j]][0];
im[j] = [im[i], im[i] = im[j]][0]
}
}
for (var hN = 1; hN * 2 <= N; hN *= 2)
for (i = 0; i < N; i += hN * 2)
for (j = i; j < i + hN; j++) {
var cos = Math.cos(Math.PI * (j - i) / hN),
sin = Math.sin(Math.PI * (j - i) / hN);
var tre = re[j + hN] * cos + im[j + hN] * sin,
tim = -re[j + hN] * sin + im[j + hN] * cos;
re[j + hN] = re[j] - tre;
im[j + hN] = im[j] - tim;
re[j] += tre;
im[j] += tim;
}
}
There is one statement in for loop for循环中只有一条语句
for (var j = 0, h = i, k = N; k >>= 1; h >>= 1)
I wonder how to write this for loop in Python? 我不知道如何在Python中编写此for循环? The k
s array and h
s array are not very clear to me so I do not know how to use zip
. 我不太清楚k
数组和h
数组,所以我不知道如何使用zip
。
One possible way is with a while loop: 一种可能的方式是使用while循环:
j = 0
h = i
k = N >> 1
while k > 0:
... # current logic in the for loop
k >>= 1
h >>= 1
The simplest way is described by @fileyfood500. 最简单的方法由@ fileyfood500描述。
Another approach could be to separate out the k
, h
logic in a generator, and using a for
loop: 另一种方法可能是在生成器中分离出k
, h
逻辑,并使用for
循环:
def gen(k, h):
while k >> 1:
yield h
h >>= 1
k >>= 1
for i in range(N):
j = 0
for h in gen(N, i):
j = (j << 1) | (h & 1)
If you do this you can reduce
the loop: 如果这样做,可以reduce
循环:
from functools import reduce # Py3
for i in range(N):
j = reduce(lambda j, h: (j << 1) | (h & 1), gen(N, i), 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.