Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

class - 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 i.e 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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...