使用两个变量创建sympy函数

huangapple go评论59阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2023年3月12日 18:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定