将 numpy ndarray 作为 fsolve 函数的输入传递 [英] passing numpy ndarray as inputs of a fsolve function

查看:76
本文介绍了将 numpy ndarray 作为 fsolve 函数的输入传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对非线性方程组进行数值求解并将 numpy ndarrays 作为输入传递.考虑下面的任意代码:

I want to numerically solve a system of nonlinear equations and pass numpy ndarrays as inputs. Consider the arbitrary code below:

import numpy as np
from scipy.optimize import fsolve

def eqs(A, B, C, D):
    eq1 = (A - B * np.sin(C)).tolist()
    eq2 = [5 * B + D * np.sum(A * np.cos(C))]
    return eq1 + eq2

n = 3

A = np.zeros((n))
A0 = np.random.rand(n)
B = 0.0
B0 = np.random.rand(1)[0]

C = np.random.rand(n)
D =  np.random.rand(1)[0]

sol = fsolve(func = eqs, x0 = [A0, B0], args = [C, D])

导致

缺少必需的位置参数

错误并将函数更改为:

def eqs(A, B, C, D):
    eq1 = A - B * np.sin(C)
    eq2 = C[0] * B + D * np.sum(A * np.cos(C))
    return [eq1, eq2]

也无济于事.但是,我非常怀疑该错误与传递 ndarrays 有什么关系.一种方法可能是将所有 ndarray 来回更改为 python 列表.但是我将无法使用 numpy 的矢量化函数,例如 np.sin()...

also doesn't help. However, I highly doubt that the error has anything to do with passing ndarrays. One approach could be to change all the ndarrays to python lists back and forth. But then I would not be able to use numpy's vectorized functions like np.sin()...

如果您能帮助我知道应该如何做,我将不胜感激.

I would appreciate if you could help me know how this should be done.

P.S. 上面的方程只是任意的,它们可能根本没有解.

P.S. Equations above are just arbitrary and they may not have solutions at all.

推荐答案

检查这是否能解决你的方程:

Check if this solve your equation:

import numpy as np
from scipy.optimize import fsolve

def eqs(X, Y):
    A, B = X[:3], X[3]
    C, D = Y[:3], Y[3]
    eq1 = A - B * np.sin(C)
    eq2 = C[0] * B + D * np.sum(A * np.cos(C))
    return np.append(eq1, eq2)

n = 3

A = np.zeros((n))
A0 = np.random.rand(n)
B = 0.0
B0 = np.random.rand(1)[0]

C = np.random.rand(n)
D =  np.random.rand(1)[0]

sol = fsolve(func = eqs, x0 = np.append(A0, B0), args = np.append(C, D))
sol

输出:

array([ 0.e+000, -1.e-323,  5.e-324, -1.e-323])

这篇关于将 numpy ndarray 作为 fsolve 函数的输入传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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