【发布时间】:2021-01-12 00:02:23
【问题描述】:
我试图找到几条直线的零点,一次用 fsolve 函数解决其中一条。我无法编写一个体面的代码来做到这一点,这是我迄今为止最好的尝试,非常感谢任何帮助。我认为最好的方法是定义一个类(该类是具有两个属性的线,即斜率和 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])
【问题讨论】:
-
“这不正确”是什么意思?输出是什么?你希望它是什么?
-
您好@Code-Apprentice 我的意思是该行不正确(解释器不会理解该行)。我之所以写它,是因为我认为它很好地反映了我希望程序做什么,所以解释一下自己会很有用。在嵌套循环中,我想找到直线的零点,但在每次循环迭代中,线参数 (m,n) 应该改变,即每次都是我正在求解的不同方程
-
“行不正确”和“解释器无法理解该行”仍然没有告诉我们运行代码时会发生什么。请edit您的问题在您运行程序时显示确切的输出。
-
这里的问题是你没有正确使用
fsolve()。我建议你找一些教程并阅读文档以了解如何正确调用它来做你想做的事情。
标签: python class scipy-optimize