![](/img/trans.png)
[英]Solving nonlinear systems of equations using Python's fsolve function
[英]Solving equations with parameters Python fsolve
我试图用 fsolve function 一次找到几条直线的零点来解决其中一条。 我无法编写一个体面的代码来做到这一点,这是我迄今为止最好的尝试,非常感谢任何帮助。 我认为最好的方法是定义一个 class (class 是具有两个属性的线,即斜率和 y 截距),但我不知道该怎么做。
import numpy as np
from scipy.optimize import fsolve
def straight_line(parameters):
m = parameters[0] # This is the first parameter of the line i.e the slope
n = parameters[1] # This is the second parameter of the line i.e. the y-axis intercept
x = parameters[3] # This is the variable of the function, I want to find x such that m * x + n = 0
return m * x + n
for m in range(-10,10):
for n in range(-10,10):
guess = 1
zero = fsolve(straight_line([m, n]), guess) # This is not correct
print([m, n, zero])
zero = fsolve(straight_line([m, n]), guess)
问题是您调用straight_line()
并将计算值发送到fsolve
。 如果您阅读文档,您会看到fsolve
的第一个参数必须是“可调用的”。 换句话说,您需要传递 function 本身:
zero = fsolve(straight_line, guess)
您还需要传递args
来定义直线,在这种情况下是斜率和 y 截距:
zero = fsolve(straight_line, guess, args=(m, n))
此外,您必须确保x
值是straight_line()
的第一个参数:
def straight_line(x, m, b):
return m*x + b
我没有测试过这个,所以它可能不完全正确。 它可能无法解决所有问题。 我建议您阅读更多教程和示例以了解其工作原理。 请参阅文档以确保您正确使用fsolve()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.