如何找到方程的根,其中变量是函数的输出,目标变量本身作为参数?



我正在尝试求解python中变量"X"的方程,其中方程中的一些变量("ABC,PQR"(是从函数"计算"输出的。问题是,为了从函数中获得输出,我需要将变量 X 作为参数本身传递。我有点陷入了循环。 我尝试了两种不同的方法,但没有取得任何成功。有没有办法解方程?

任何帮助/指导都非常感谢。

我的第一个方法是从一个小值开始并运行一个循环。我尝试使用 math.isclose((,但一旦值超出范围并且它进入无限循环,就会收到"数学绑定错误"。 第二种方法是编写完整的表达式并使用scipy.optimize fsolve((,但我无法理解如何正确实现它。

# function
def calculations(X, a, b, c):
ABC = X*a*b + c
XYZ = X*b*c + a
PQR = X*a*c + b
return ABC, XYZ, PQR
# ABC, PQR is the output from a function which uses X as input
# solve for X
func = 2*ABC + sqrt(PQR*ABC) + X*100*0.5
# Approach 1
X = 0.001
step = 0.001
while True:
# function call
Var_ABC, Var_XYZ, Var_PQR = calculations(X, a, b, c)
func = 2*Var_ABC + math.sqrt(Var_PQR * Var_ABC) + X*100*0.5
if (math.isclose(func, 0.0, rel_tol=0.1) == True):
break
else:
X = X + step
# Approach 2
# Since I don't know the value of X, how can I get the output from the function and then solve it again?
func_output[0] = calculations(X, a, b, c) # ABC
func_output[2] = calculations(X, a, b, c) # PQR
func = 2* func_output[0] + math.sqrt (func_output[0] * func_output[2] ) + X*100*0.5
from scipy.optimize import fsolve
desired_output_X = fsolve(func, [0.01, 1])

这可以帮助您开始使用fsolve

# function of X
def func(X):
func_output = calculations(X, a, b, c)
func = 2* func_output[0] + math.sqrt (func_output[0] * func_output[2]) + X*100*0.5
return func
# extra arguments for calculations function, dummy values used: set them as desired
a,b,c = 1,2,6
# initiating X = 0.01 and solve for X
desired_output_X = fsolve(func, x0 = 0.01)

最新更新