首页 > 解决方案 > 如何用 sin、cos 函数绘制隐式函数并在 pyhton 中找到根?

问题描述

我有这样的功能

cos(x) - sin(y) + 0.2 = 0

我想在 plt.plot 中绘制这个函数并在函数 = 0 时找到根 (x,y),这是我的代码

from scipy import optimize
import numpy as np
   
def func_2(x):
    return np.cos(x[0])-np.sin(x[1])+0.2

result = optimize.root(func_2, [1])

我得到了错误

IndexError                                Traceback (most recent call last)
<ipython-input-366-6d13d246d69c> in <module>
     14 
     15 result = optimize.root(func_1, [1])
---> 16 result1 = optimize.root(func_2, [1])

~\anaconda3\lib\site-packages\scipy\optimize\_root.py in root(fun, x0, args, method, jac, tol, callback, options)
    185 
    186     if meth == 'hybr':
--> 187         sol = _root_hybr(fun, x0, args=args, jac=jac, **options)
    188     elif meth == 'lm':
    189         sol = _root_leastsq(fun, x0, args=args, jac=jac, **options)

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _root_hybr(func, x0, args, jac, col_deriv, xtol, maxfev, band, eps, factor, diag, **unknown_options)
    211     if not isinstance(args, tuple):
    212         args = (args,)
--> 213     shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
    214     if epsfcn is None:
    215         epsfcn = finfo(dtype).eps

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
     24 def _check_func(checker, argname, thefunc, x0, args, numinputs,
     25                 output_shape=None):
---> 26     res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
     27     if (output_shape is not None) and (shape(res) != output_shape):
     28         if (output_shape[0] != 1):

<ipython-input-366-6d13d246d69c> in func_2(x)
     11 
     12 def func_2(x):
---> 13     return np.cos(x[0])-np.sin(x[1])+0.2
     14 
     15 result = optimize.root(func_1, [1])
IndexError: index 1 is out of bounds for axis 0 with size 1

标签: pythonfunctionimplicit

解决方案


推荐阅读