问题
I want to draw an inverse proportional function with GraphScene, everything works, However when I set condition of x != 0
, a SyntaxError pops:
f11 = self.get_graph(lambda x: 1/x if x!= 0)
SyntaxError: invalid syntax
the error indicates the last parenthesis
I searched a lot, the lambda x: 1/x if x!= 0
should be a correct python syntax, don't know why it not work! thanks for any help.
回答1:
Add an else
telling what the lambda should evaluate to when x==0
, and suddenly you have valid syntax:
lambda x: 1/x if x != 0 else 0
This syntax construct was added in PEP-308, which was adopted in Python 2.5. From the PEP, the grammar changes are described as follows:
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
...
testlist_safe: or_test [(',' or_test)+ [',']]
...
gen_for: 'for' exprlist 'in' or_test [gen_iter]
As you can see, else
is mandatory; there's no way to have a test
without both an if
and an else
.
回答2:
Graphs are created using bezier curves, bezier curves cannot be discontinuous, therefore, you must create multiple graphs for each domain you want to use.
class AddingDomains(GraphScene):
CONFIG = {
"y_max" : 5,
"y_min" : -5,
"x_max" : 6,
"x_min" : -6,
"graph_origin": ORIGIN,
}
def construct(self):
self.setup_axes()
graph_left = self.get_graph(lambda x : 1/x,
color = GREEN,
x_min = self.x_min,
x_max = 1/self.y_min
)
graph_right = self.get_graph(lambda x : 1/x,
color = GREEN,
x_min = 1/self.y_max,
x_max = self.x_max
)
graph=VGroup(graph_left,graph_right)
self.play(
ShowCreation(graph),
run_time = 2,
rate_func= double_smooth
)
self.wait()
Or
class AddingDomains2(GraphScene):
CONFIG = {
"y_max" : 5,
"y_min" : -5,
"x_max" : 6,
"x_min" : -6,
"graph_origin": ORIGIN,
}
def construct(self):
self.setup_axes()
graph_left = self.get_graph(lambda x : 1/x,
color = GREEN,
x_min = self.x_min,
x_max = 1/self.y_min
)
graph_right = self.get_graph(lambda x : 1/x,
color = GREEN,
x_min = 1/self.y_max,
x_max = self.x_max
)
graph=VMobject(color=RED)
graph.append_points(graph_left.points)
graph.append_points(graph_right.points)
self.play(
ShowCreation(graph),
run_time = 2,
rate_func= double_smooth
)
self.wait()
Returns: More information in manimlib/mobject/types/vectorized_mobject.py and manimlib/mobject/functions.py.
来源:https://stackoverflow.com/questions/57182904/lambda-with-condition-x-1-x-if-x-0-not-work