0

I wish to write a for loop such that the stopping criterion is that which satisfies a difference between two consecutive elements in a list. The list is appended from the for loop as shown in the code below:

m, n = 100, 4
counter1 = []
tol = 1e-8

x_not = np.zeros(n)
for iterate in range(100):
    for rows in range(m):
        y = My_func(x_not, rows)
        x_not = y
        counter1.append(norm(x_not))
        if counter1[i-1] - counter1[i] < tol:
            break

I wish the for loop to stop whenever any two consecutive elements is less than tol. I need someone to help implement this code in Python. My_func is a predefined function.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
MaliMali
  • 37
  • 5
  • 2
    Which for loop are you referring to? – quamrana Sep 04 '20 at 21:33
  • Hi, MaliMali, what have you tried so far? You'll get a much better response from the community if you show what you've tried and you have a specific question. – Christian Dean Sep 04 '20 at 21:34
  • I actually included a sample code in my post – MaliMali Sep 04 '20 at 21:35
  • 1
    `counter1[-1]` will _always_ give you the last element of `counter1`. `counter1[-2]` will give you the last-but-one. Because you append to `counter1`, the last element is what you just appended. The last-but-one is the one you appended before that. – Pranav Hosangadi Sep 04 '20 at 21:36
  • 1
    Also, you can only compare two elements from your list after the second element has been appended. – quamrana Sep 04 '20 at 21:42
  • 1
    Maybe you could insert this code into a function and call return. – Carlos Bazilio Sep 04 '20 at 21:43
  • @Pranav Honsangadi No it does not. I actually wanted a situation where the difference between any two elements of the list _counter1_ is less than _tol_ – MaliMali Sep 04 '20 at 21:46
  • Can you give an example of an input, and show what values would cause the desired output? – damon Sep 04 '20 at 21:52
  • @damon counter1 = [0.1, 1.2, 1.22222222, 1.22222221] I wish to make the loop to stop in this case when i = 3 since counter1[3] - counter1[2] < tol – MaliMali Sep 04 '20 at 22:01
  • What doesn't work with your current code? – Prune Sep 04 '20 at 22:02
  • @Prune The error I got was: 'i is not defined' – MaliMali Sep 04 '20 at 22:06
  • You need to define `i` for that expression to work; that is not a difficult problem. Since you're working with only the last two elements, why do you need the entire list and a custom index? – Prune Sep 04 '20 at 22:07
  • @Prune Because the list is always updated with _append_ from the loop – MaliMali Sep 04 '20 at 22:11
  • You need only the two most recent values, not the entire history. You don't need an index variable to get the last two values. – Prune Sep 04 '20 at 22:31
  • @Prune Thank you. I get the logic now – MaliMali Sep 04 '20 at 23:20
  • @Pranav Honsangadi Thanks for your earlier comment. I later realised the logic in your post. – MaliMali Sep 04 '20 at 23:21

0 Answers0