How to translate an iterative formula into Python

Viewed 48

I'm a beginner in Python and i'm trying to translate this formula into Python to create a vector thanks to a boucle for :

CN formula

I tried this code:

CN_mod_0 = []
CN = []
CN[0] = 35
for i in range(1,96):
    CN[i] = 1200 / (1200/CN[i-1] + (e_num_H_0[i]- (p_num_H_0[i-1] - d_num_H_0[i-1])))
    CN_mod_0.append(CN[i])
CN_mod_0

But there is something wrong with the initial value CN[0] that I entered... The vectors e_num_H_0, p_num_H_0 and d_num_H_0 have all a length of 96.

Thank you very much for the help

1 Answers

Just to clarify, you can initialize the list with elements already in it.

CN = [35]

In this case, where you want to initialize the CN with 96 elements, you can either do: CN = [0] * 96

which gives you a list of length 96 that is filled with 0s or you can use numpy:

import numpy as np
CN = np.zeroes(96)

which gives you array of length 96, again filled with 0s. And as you iterate through the for loop, your CN array at the i-th position will be updated with the value your formula calculates. Lastly, I should mention that python indexing starts at 0 so your for loop should be:

for i in range(95):
    # do something

This will start counting at 0th index and count up the last element which is the 95th index.

Related