简体   繁体   中英

What is the pythonic way to write this mathematical formulas?

This is my first post in stackoverflow.com . I am beginner in python and in programming in general. I read everywhere that the best way to learn programming is to start programming. Therefore, i have encountered the following table and i would like to make a function so i can calculate the relative motion in relation to the x-coordinate.

relative motion table

在此处输入图片说明

assuming that {C_b , n, C, L} are known i have coded the table as following:

if x = 0:
    h1_M = 0.42*n*C*(C_b+0.7)

    if C_b < 0.875:
        h1 = 0.7*((4.35/sqrt(C_b))-3.25)*h1_M
    else:
        h1 = h1_M

elif x>0 and x<0.3*L:

    h1_M = 0.42*n*C*(C_b+0.7)
    h1_AE = 0.7*((4.35/sqrt(C_b))-3.25)*h1_M
    h1 = h1_AE - ((h1_AE-h1_M)/0.3)*(x/L)

elif x>=0.3*L and x<0.7*L:

    h1 = 0.42*n*C*(C_b+0.7)

elif x>0.7*L and x<L:
    h1_M = 0.42*n*C*(C_b+0.7)
    h1 = h1_M + ((h1_FE - h1_M)/0.3)*((x/L)-0.7)

elif x==L:
    h1_M = 0.42*n*C*(C_b+0.7)
    h1 = ((4.35/sqrt(C_b))-3.25)*h1_M

Is this the pythonic way to structure my function? Thank you for you reply

It not just about “Pythonic” way to write this function, but a problem regarding the programming practice. From my perspective, I would suggest you to break each step to a properly named routine, and name each value according to its meaning instead of a single letter variable.

def your_funcion(C_b, n, C, L):
    h1_M = 0.42*n*C*(C_b+0.7)
    if x == 0:
        if C_b < 0.875:
            return 0.7*((4.35/sqrt(C_b))-3.25)*h1_M
        return h1_M
    if x < 0.3*L:
        h1_AE = 0.7*((4.35/sqrt(C_b))-3.25)*h1_M
        return h1_AE - ((h1_AE-h1_M)/0.3)*(x/L)
    if x < 0.7*L:
        return 0.42*n*C*(C_b+0.7)
    if x < L:
        return h1_M + ((h1_FE - h1_M)/0.3)*((x/L)-0.7)
    return ((4.35/sqrt(C_b))-3.25)*h1_M

h1 = your_function(C_b, n, C, L)

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