mardi 7 septembre 2021

How to use a "while loop" to iterate in a non-sequential way and update limits of a range?

I'm simplifying an engineering problem as much as possible for this question:

I have a working code like this:

import numpy as np
# FUNCTION DEFINITION
def Calculations(a, b):   # a function defined to work based on 2 arguments, a and b
    A = a * b - a
    B = a * b - b
    d = A - B
    return(A, B, d, a, b)

# STORE LIST CREATION
A_list = []
B_list = []
d_list = []
a_list = []
b_list = []   # I will need this list later

# 1st sequential iteration in a for loop
length = np.arange(60, 62.5, 0.5)
for l in length: 
    lower = 50  # this is what I want the program to update based on d
    upper = 70.5  # this is what I want the program to update based on d
    step = 0.5
    width = np.arange(lower, upper, step)
# 2nd for loop, but here I wouldn't like a sequential iteration
    for w in width:
        A_list.append(Calculations(l, w)[0])
        B_list.append(Calculations(l, w)[1])
        d_list.append(Calculations(l, w)[2])
        a_list.append(Calculations(l, w)[3])
        b_list.append(Calculations(l, w)[4])
        
        
print(A_list, " \n")
print(B_list, " \n")
print(d_list, " \n")
print(a_list, " \n")
print(b_list, " \n")

This is the way I have it now, but not how I want it to work.

Here, the program iterates each time through the values of length(l) in a sequential manner, meaning it evaluates everything for l=60, then for l=60.5 and so on... this is ok, but then, for l=60 it evaluates first for w=50, then for w=50.5 and so on...

What I want is that, for l=60 he evaluates for any random value (let's call this n) between the 50 (lower) and 70.5 (upper) with a step of 0.5 (step), he will then find a particular d as one of the "returned" results, if the d is negative then the n he used is the new lower, if d is positive that n is the new upper, and he will continue to do this until d is zero.

I will keep trying to figure it out by myself, but any help would be appreciated.

PD: As I said this example is a simplification of my real problem, as side questions I would like to now:

  • The condition of while loop to break is not when d is zero, but the closest possible to zero, or phrased in other way, the min() of the abs() values composing the d_list. I tried something like:
for value in d_list: 
    if value = min(abs(d_list)):      
        print(A_list, " \n")
        print(B_list, " \n")
        print(d_list, " \n")
        print(a_list, " \n")
        print(b_list, " \n")

but that's not correct. Thanks in advance




Aucun commentaire:

Enregistrer un commentaire