英文:
Making sympy function with 2 variables
问题
我试图使用sympy做一个分段函数,但我做不到。它不能识别分段函数。我想要一个简单的函数,当(x, y)不等于(0, 0)时为a,当(x, y)等于(0, 0)时为a。有人可以帮帮我吗?
非常感谢
我尝试了这段代码:
f_exp = sp.Piecewise((((x*y)*(x**2 - y**2)) / (x**2 + y**2), (x,y) != (0,0)), (a, (x,y) == (0,0)))
f = sp.Lambda((x,y), f_exp) # Create the function
display(f)
英文:
I´m trying to do a piecewise function with sympy, but I can´t. It doesn´t the piecewise function.
I want a simple funtion when (x,y) != (0,0) and a when (x,y) = (0,0)
Can someone help me ?
Thank you so much
I tried this code:
f_exp = sp.Piecewise((((x*y)*(x**2 - y**2)) / (x**2 + y**2), (x,y) != (0,0)), (a, (x,y) == (0,0)))
f = sp.Lambda((x,y), f_exp) # Creamos la función
display(f)
答案1
得分: 1
你不能写(x, y) != (0, 0)
,因为Python在Sympy之前拦截这些代码,并执行比较:在这种情况下,显然元组(x, y)
与(0, 0)
不同。
因此,你需要手动构建这种关系。以下是两种实现方式:
f_exp = Piecewise((((x*y)*(x**2 - y**2)) / (x**2 + y**2), And(Ne(x, 0), Ne(y, 0))), (a, True))
f_exp = Piecewise((a, Eq(x, 0) & Eq(y, 0)), (((x*y)*(x**2 - y**2)) / (x**2 + y**2), True))
英文:
You can't write (x,y) != (0,0)
because Python intercept that codes before Sympy, and it performs the comparison: in this case, clearly the tuple (x, y)
is different from (0, 0)
.
Hence, you'd have to manually construct the relationship. Here are two ways to achieve it:
f_exp = Piecewise((((x*y)*(x**2 - y**2)) / (x**2 + y**2), And(Ne(x, 0), Ne(y, 0))), (a, True))
f_exp = Piecewise((a, Eq(x, 0) & Eq(y, 0)), (((x*y)*(x**2 - y**2)) / (x**2 + y**2), True))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论