简体   繁体   English

定义包含不等式的函数

[英]defining a function that contains an inequality

I want to make a define a function f(x,t) such that f(x,t) = 1 when 0.1 <= x <= 0.3 , and it is 0 otherwise. 我想定义函数f(x,t) ,使得f(x,t) = 1 when 0.1 <= x <= 0.3 ,否则为0

I wasn't sure how to do this with the normal def command in python. 我不知道如何使用python中的普通def命令执行此操作。 I was trying to add elif statement in the definition but it's not working out for me. 我试图在定义中添加elif语句,但它不适合我。

You could use an if statement inside the function: 你可以在函数中使用if语句:

def f(x,t):
    if 0.1 <= x <= 0.3:
        return 1
    return 0

or, more elegantly, you could just convert the boolean expression to an int , since True will become 1 and False will become 0 : 或者,更优雅的是,您可以将布尔表达式转换为int ,因为True将变为1False将变为0

def f(x,t):
    return int(0.1 <= x <= 0.3)

Also note that since the return value depends only on x , you can remove t from the function's definition. 另请注意,由于返回值仅取决于x ,因此可以从函数的定义中删除t

def f(x, t):
    return 1 if 0.1 <= x <= 0.3 else 0

I don't see why you need elif here. 我不明白为什么你需要这里的elif You can define the condition as 0.1 <= x <= 0.3 , and since a True maps to 1 and False to 0 if you call int(..) , you can define this as: 您可以将条件定义为0.1 <= x <= 0.3 ,并且因为如果调用int(..) ,则True映射到1并且False0 ,您可以将其定义为:

def f(x, t):
    return int(0.1 <= x <= 0.3)

But I think it makes sense to return a bool anyway. 但我觉得无论如何都要回归一个bool是有道理的。 A bool is after all a subclass of int , and both 1 == True and 0 == False hold. bool毕竟是int子类 ,并且1 == True0 == False hold。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM