簡體   English   中英

如何使用 SymPy 求解兩個變量方程以使其依賴於一個變量?

[英]How can I solve a two variable equation for it to depend on one variable with SymPy?

我一直在嘗試為一個項目制作一個優化計算器。 我正在做一個正方形面積的基本示例。 為了得到一個我需要推導的方程,我必須求解 P=XY,所以我希望它顯示的表達式是 Y =P/X。 我計划讓它比僅僅允許整數作為輸入更容易訪問,所以我正在嘗試這樣的求解器方法:

from sympy import *
x, y, p = symbols('x y z')
AExp = x*y
print(solve((x*y),p))

但我得到了錯誤

ValueError:
Since there is more than one variable in the expression, the
variable(s) of differentiation must be supplied to differentiate

其他求解器似乎用於更復雜的表達式,所以我懷疑是否應該使用它們以及如何使用它們。

不確定錯誤消息,但問題中的代碼存在一些問題:

  • x, y, p = symbols('xy z')創建xy ,它們打印為 'x' 和 'y' 和p將打印為 'z'
  • AExp = x*y :創建一個作為xy乘積的表達式
  • solve((x*y),p) :嘗試為方程x*y = 0找到一個p

這是一些代碼來查找y使得p = x*y

from sympy import *
x, y, p = symbols('x y p', real=True) # telling sympy which type of solutions to search for helps prevent misunderstandings
my_expr = x*y
my_eq = Eq(my_expr, p)   # equation x*y = p
print(solve(my_eq, y))   # find a y for the equation
print(solve(Eq(x*y, p), y))   # shorthand for the same

這輸出: [p/x]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM