[英]How to calculate and output multiple results according to one equation in python?
So I know how to define the function, but I don't know how to output two results where t=0
and t=1
. 所以我知道如何定义函数,但是我不知道如何输出两个结果,其中t=0
和t=1
。
Here is my code: 这是我的代码:
from math import exp
from math import pi
from math import sin
def g(t):
a = exp(-t)
b = sin(pi*t)
g = a*b
return g
t=0
print(g)
g
is a function. g
是一个函数。 print(g)
literally prints the function object. print(g)
从字面上打印功能对象。 print(g(t))
prints the function g
evaluated at t
. print(g(t))
打印在t
求值的函数g
。 So, you want this after the definition of g
: 因此,您需要在g
定义之后:
print(g(0)) # Print g evaluated at t=0
print(g(1)) # Print g evaluated at t=1
Don't do g = a * b
. 不要做g = a * b
。 Rename it something like h
. 重命名为h
。 By doing that, you're redefining g
to mean something different in the local scope which can get confusing. 通过这样做,您将g
重新定义为表示本地范围中可能会引起混淆的其他内容。 Functions are objects too! 功能也是对象!
For your g
function, you use a total of 3 intermediate variables. 对于您的g
函数,您总共使用了3个中间变量。 Normally, having intermediate variables is useful for readability. 通常,具有中间变量对于提高可读性很有用。 Here, it's not necessary: 在这里,没有必要:
def g(t):
return exp(-t) * sin(pi * t)
(This makes it resemble the task more anyway...) (这使它更像是任务...)
If you want to call your function more times in the future, you could put your arguments into a list and do this: 如果您希望将来多次调用函数,可以将参数放入列表中并执行以下操作:
for arg in [0, 1]:
print(g(arg))
Also, you can return the value directly without re-assigning to g
: 另外,您可以直接返回值,而无需重新分配给g
:
def g(t):
a = exp(-t)
b = sin(pi*t)
return a*b
Python uses tuples to return multiple values from a function: Python使用元组从一个函数返回多个值:
def two_vals():
return 11,22
>>> two_vals()
(11, 22)
You can use tuple expansion to assign multiple values to multiple named values: 您可以使用元组扩展将多个值分配给多个命名值:
>>> g1, g2=two_vals()
>>> g1
11
>>> g2
22
So. 所以。 Rewrite your function so that it calculates both values. 重写您的函数,以便它计算两个值。 Return both (as a list, tuple, dict, whatever data structure) and you have your two values to print. 返回两者(作为列表,元组,字典,任何数据结构),然后您就有两个值要打印。
To fulfill this assignment however, you could just call g
twice and place into a string to print: 但是,要完成此任务,您可以调用两次g
并将其放入字符串中进行打印:
def g(t):
a = exp(-t)
b = sin(pi*t)
g = a*b
return g
def both_g_str():
return "g(0): {}, g(1): {}".format(g(0), g(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.