如何在fsolve中包含可调参数? [英] How to include adjustable parameter in fsolve?

查看:129
本文介绍了如何在fsolve中包含可调参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 中的 fsolve 越来越熟悉,但在我的非线性方程系统中包含可调参数时遇到了问题.

如果你想找到正解和负解,你需要将你的初始猜测作为数组传递(有人问过类似的问题 此处).这是更新的版本

z = 1初始 = [[-2,-1],[2,1]]溶胶 = []对于 i 在范围内(len(初始)):sol.append(so.fsolve(test, initial[i], args = (z)))打印(np.array(溶胶))

输出是

[[-0.5 -1.32287566][-0.5 1.32287566]]

I'm getting familiar with fsolve in Python and I am having trouble including adjustable parameters in my system of nonlinear equations. This link seems to answer my question but I still get errors. Below is my code:

 import scipy.optimize as so

 def test(x,y,z):
    
     eq1 = x**2+y**2-z
     eq2 = 2*x+1
    
     return [eq1,eq2]

     z = 1                                         # Ajustable parameter
     sol = so.fsolve(test , [-1,2] ,args=(z))      # Solution Array
     print(sol)                                    # Display Solution

The output gives

    TypeError: test() missing 1 required positional argument: 'z'

When z is clearly defined as an argument. How do I include this adjustable parameter?

解决方案

So before posting here I should have spent a little bit more time playing with it. Here is what I found

import scipy.optimize as so
import numpy as np

def test(variables,z): #Define function of variables and adjustable arg
    
    x,y = variables     #Declare variables
    
    eq1 = x**2+y**2-1-z #Equation to solve #1
    eq2 = 2*x+1         #Equation to solve #2
    
    return [eq1,eq2]    #Return equation array

z = 1                                       #Ajustable parameter
initial = [1,2]                             #Initial condition list                          
sol = so.fsolve(test , initial, args = (z)) #Call fsolve
print(np.array(sol))                        #Display sol  

With an output

[-0.5         1.32287566]

I'm not the best at analyzing code, but I think my issue was that I had mixed up my variables and arguments in test(x,y,z) such that it didn't know what I was trying to apply the initial guess to.

Anyway, I hope this helped someone.

edit: While I'm here, the test function is a circle of adjustable radius and a line that intersects it at two points.

If you wanted to find the positive and negative solutions, you'd need to pass your initial guess in as an array (someone asked a similar question here). Here is the updated version

z = 1
initial = [[-2,-1],[2,1]]
sol = []                            
for i in range(len(initial)): 
   sol.append(so.fsolve(test , initial[i], args = (z))) 
print(np.array(sol)) 

The output is

[[-0.5        -1.32287566]
 [-0.5         1.32287566]]

这篇关于如何在fsolve中包含可调参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆