简体   繁体   中英

How can I get Python to print out the answer of an equation multiple times with a list of different input variables?

as you could probably tell from the code below I'm very new to python. I have no doubt that this questions has been answered somewhere on this site but I can't find it.

I have an equation solving for k4 that has three variables (cr, q, and qmax). qmax is a constant - that I would like to be set at 11.2.

In the code I have individually defined the value for each variable to solve for one specific k4 value.

import math

cr = 1
q = 3.8
qmax = 11.2

k4 = cr * ((-math.log(1 - ((q / qmax) ** (1 / 3)))) +
           (0.5 * math.log(1 + ((q / qmax) ** (1 / 3)) + ((q / qmax) ** (2 / 3)))) +
           (math.sqrt(3) * math.atan(((math.sqrt(3)) * ((q / qmax) ** (1 / 3))) / (2 + ((q / qmax) ** (1 / 3))))))

print(k4)

What I want to do is have python input a list of values for each of the variables and print out the answer. Right now the code is limited to manually typing out each variable and then printing out only one k4 value.

The list I have is this: (it's not code but I formatted it so it looks like a table)

cr   q
1    3.8
3    0.5
7    0.1
10   0.01

Thank you for your help!

You can iterate over each pair of cr and q values:

import math

q_max = 11.2
value_pairs = [(1, 3.8), (3, 0.5), (7, 0.1), (10, 0.01)]

for cr, q in value_pairs:
    k4 = cr * ((-math.log(1 - ((q / qmax) ** (1 / 3)))) +
           (0.5 * math.log(1 + ((q / qmax) ** (1 / 3)) + ((q / qmax) ** (2 / 3)))) +
           (math.sqrt(3) * math.atan(((math.sqrt(3)) * ((q / qmax) ** (1 / 3))) / (2 + ((q / qmax) ** (1 / 3))))))

    print(k4)    


Defining the calculation as a function will help you.Try:

import math
def calcu(*args):
    print('cr  q  qmax  k4')
    for i in args:
        cr,q,qmax = i[0],i[1],i[2]
        k4 = cr * ((-math.log(1 - ((q / qmax) ** (1 / 3)))) +(0.5 * math.log(1 + ((q / qmax) ** (1 / 3)) + ((q / qmax) ** (2 / 3)))) +(math.sqrt(3) * math.atan(((math.sqrt(3)) * ((q / qmax) ** (1 / 3))) / (2 + ((q / qmax) ** (1 / 3))))))
        print(cr , q , qmax,k4)

Now give your values as list, like:

calcu([1,2,3],[2,3,4])

Now if you have the qmax fixed:

import math
qmax = 'some number'
def calcu(*args):
    print('cr  q  k4')
    for i in args:
        cr,q = i[0],i[1]
        k4 = cr * ((-math.log(1 - ((q / qmax) ** (1 / 3)))) +(0.5 * math.log(1 + ((q / qmax) ** (1 / 3)) + ((q / qmax) ** (2 / 3)))) +(math.sqrt(3) * math.atan(((math.sqrt(3)) * ((q / qmax) ** (1 / 3))) / (2 + ((q / qmax) ** (1 / 3))))))
        print(cr , q ,k4)

Now call it, like:

calcu([1,2],[2,3])

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