sympy assumptions in nsolve not holding

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

sympy assumptions in nsolve not holding

问题

I am trying to solve 2 simultaneous equations, which lead to two sets of x-y values. I only want the x-y set that has a positive x.

我试图解决两个同时出现的方程,这将导致两组x-y值。我只想要x为正的那组x-y值。

I set my assumption in x when defining it to be positive=True. Yet when I get my x-y solutions, I still only get the [-1.41421356237310], [2.00000000000000] set when I want [1.41421356237310], [2.00000000000000] set. It appears that my assumption to make x positive is not working, although the print((x).is_positive() returns True. Why is my assumption not working, and how do I force nsolve to assume that x must be positive? The code can be found below.

我在定义x时将它的假设设置为positive=True。然而,当我获得x-y的解时,我仍然只得到[-1.41421356237310], [2.00000000000000]这组值,而我想要的是[1.41421356237310], [2.00000000000000]这组值。看来我的假设x为正并没有起作用,尽管print((x).is_positive)返回True。为什么我的假设不起作用,我如何强制nsolve假定x必须为正?下面是代码。

import sympy as sym

x = sym.symbols('x', positive=True)
y = sym.symbols('y', positive=True)
eq1 = sym.Eq(y, x**2)
eq2 = sym.Eq(y, 2)
result = sym.nsolve((eq1, eq2), (x, y), (-1, -5))
print(result)
print((x).is_positive)
英文:

I am trying to solve 2 simultaneous equations, which lead to two sets of x-y values. I only want the x-y set that has a positive x.

I set my assumption in x when defining it to be positive= True. Yet when I get my x-y solutions, I still only get the [-1.41421356237310], [2.00000000000000] set when I want [1.41421356237310], [2.00000000000000] set. It appears that my assumption to make x positive is not working, although the print((x).is_positive() returns True. Why is my assumption not working, and how do I force nsolve to assume that x must be positive? The code can be found below.

import sympy as sym

x = sym.symbols('x', positive= True)
y= sym.symbols('y', positive= True)
eq1= sym.Eq(y,x**2)
eq2= sym.Eq(y,2)
result= sym.nsolve((eq1, eq2), (x,y),(-1,-5))
print(result)
print((x).is_positive)

答案1

得分: 2

你应该使用 solve 而不是 nsolve,因为只有前者会使用变量的假设:

...
result = sym.solve((eq1, eq2), (x, y))
print(result)

如预期结果所示:

[(sqrt(2), 2)]

(如果删除 x 上的 positive=True 假设,你会得到 [(sqrt(2), 2), (-sqrt(2), 2)]

英文:

You should use solve instead of nsolve, because only the former will use the assumptions on the variables:

...
result = sym.solve((eq1, eq2), (x, y))
print(result)

gives as expected:

[(sqrt(2), 2)]

(while you get [(-sqrt(2), 2), (sqrt(2), 2)] if you remove the positive=True assumption on x)

huangapple
  • 本文由 发表于 2023年2月27日 14:23:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577315.html
匿名

发表评论

匿名网友

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

确定