Python:寻找非线性方程的多个根 [英] Python: Finding multiple roots of nonlinear equation
问题描述
假设函数如下:
f(x) = x * cos(x-4)
With x = [-2.5, 2.5]
这个函数在 f(0) = 0
和 f(-0.71238898) = 0
.
这是通过以下代码确定的:
导入数学从 scipy.optimize 导入 fsolve定义函数(x):返回 x*math.cos(x-4)x0 = fsolve(func, 0.0)# 返回 [0.]x0 = fsolve(func, -0.75)# 返回 [-0.71238898]
使用 fzero
(或任何其他 Python 根查找器)在一次调用中查找两个根的正确方法是什么?是否有不同的 scipy
函数可以做到这一点?
定义您的函数,使其可以接受标量或 numpy 数组作为参数:
<预><代码>>>>将 numpy 导入为 np>>>f = lambda x : x * np.cos(x-4)然后将参数向量传递给 fsolve
.
Assume the following function:
f(x) = x * cos(x-4)
With x = [-2.5, 2.5]
this function crosses 0
at f(0) = 0
and f(-0.71238898) = 0
.
This was determined with the following code:
import math
from scipy.optimize import fsolve
def func(x):
return x*math.cos(x-4)
x0 = fsolve(func, 0.0)
# returns [0.]
x0 = fsolve(func, -0.75)
# returns [-0.71238898]
What is the proper way to use fzero
(or any other Python root finder) to find both roots in one call? Is there a different scipy
function that does this?
Define your function so that it can take either a scalar or a numpy array as an argument:
>>> import numpy as np
>>> f = lambda x : x * np.cos(x-4)
Then pass a vector of arguments to fsolve
.
>>> x = np.array([0.0, -0.75])
>>> fsolve(f,x)
array([ 0. , -0.71238898])
这篇关于Python:寻找非线性方程的多个根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!