简体   繁体   中英

Solving equations with parameters Python fsolve

I am trying to find the zero's of several straight lines solving one of them at a time with fsolve function. I can't manage to write a decent code that will do this, this below is my best attempt so far, any help is very much appreciated. I think the best way to do it is to define a class (the class being the line with its two properties ie the slope and the y intercept) but I do not know how to do this.

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)

The problem is that you call straight_line() and send the calculated value to fsolve . If you read the documentation , you will see that the first parameter to fsolve , must be a "callable". In other words, you need to pass the function itself:

zero = fsolve(straight_line, guess)

You also need to pass the args to define the line, in this case the slope and y-intercept:

zero = fsolve(straight_line, guess, args=(m, n))

Also, you have to make sure the x value is the first parameter to straight_line() :

def straight_line(x, m, b):
    return m*x + b

I haven't tested this, so it might not be exactly correct. It might not fix all the problems. I suggest you read more tutorials and examples to learn about how this works. Refer to the documentation to be sure you are using fsolve() correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM