Python Forum
Create recursion for elementwise operation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create recursion for elementwise operation
#1
Hello everyone

I have these two operations:
[Image: f-function.png]
[Image: g-function.png]

For the base case, the length of the array is 2:
[Image: base-array.png]
and the operation in the base case is:
[Image: base-operation.png]

The problem comes when the length of the array is greater than 2 (the order is 2^n), for example, 2^2 = 4 then the array is:
[Image: array-length-4.png]
the operation become:
[Image: array-4-operation.png]

The code that I have written so far:
import numpy as np
import math

y = np.array([-0.38986815, 0.55606628, -1.52609701, 0.68725331])
n = int(math.log2(len(y)))

# function for f operation
def f(a, b):
    return 2 * aatanh(math.tanh(a / 2) * math.tanh(b / 2))

def aatanh(x):
    if x == 1:
        return math.atanh(x - 0.0000001)
    elif x == -1:
        return math.atanh(x + 0.0000001)
    else:
        return math.atanh(x)

# function for g operation
def g(a, b, c):
    return (-1 ** c) * (a + b)

def sc_dec(i):
    if i <= 1:
        up = f(y[i], y[i-1])
        down = g(y[i], y[i-1], up)
        return up, down
    else:
        up = f(y[i], sc_dec(i-1))
        down = g(y[i], sc_dec(i-1), up)
        return np.concatenate((up, down))
print(sc_dec(n))
The second part of the sc_dec function is incorrect because I don't know how to translate the operation recursively. I am looking forward to any help...
Reply
#2
(Jun-02-2022, 04:01 AM)divon Wrote: for example, 2^2 = 4 then the array is:
An example is not enough, you must write the induction relation that says how u_k is computed in terms of the previous values. This is not clear from the example.
Reply
#3
I am sorry for being late in replying to your message, for reshaping the array, I am using a dictionary then appending each row and reshaping it.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020