[英]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.正如您可能从下面的代码中看出的那样,我对 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).我有一个方程求解具有三个变量(cr、q 和 qmax)的 k4。 qmax is a constant - that I would like to be set at 11.2.
qmax 是一个常数——我想设置为 11.2。
In the code I have individually defined the value for each variable to solve for one specific k4 value.在代码中,我单独定义了每个变量的值,以求解一个特定的 k4 值。
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.我想要做的是让 python 输入每个变量的值列表并打印出答案。 Right now the code is limited to manually typing out each variable and then printing out only one k4 value.
现在代码仅限于手动输入每个变量,然后只打印一个 k4 值。
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:您可以遍历每对
cr
和q
值:
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:将计算定义为 function 将对您有所帮助。尝试:
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:现在,如果您固定了
qmax
:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.