简体   繁体   中英

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:

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 (var j = 0, h = i, k = N; k >>= 1; h >>= 1)

I wonder how to write this for loop in Python? The k s array and h s array are not very clear to me so I do not know how to use zip .

One possible way is with a while loop:

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.

Another approach could be to separate out the k , h logic in a generator, and using a for loop:

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:

from functools import reduce    # Py3

for i in range(N):
    j = reduce(lambda j, h: (j << 1) | (h & 1), gen(N, i), 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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