Python:寻找非线性方程的多个根 [英] Python: Finding multiple roots of nonlinear equation

查看:26
本文介绍了Python:寻找非线性方程的多个根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设函数如下:

f(x) = x * cos(x-4)

With x = [-2.5, 2.5] 这个函数在 f(0) = 0f(-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 函数可以做到这一点?

fzero 参考

解决方案

定义您的函数,使其可以接受标量或 numpy 数组作为参数:

<预><代码>>>>将 numpy 导入为 np>>>f = lambda x : x * np.cos(x-4)

然后将参数向量传递给 fsolve.

<预><代码>>>>x = np.array([0.0, -0.75])>>>fsolve(f,x)数组([ 0., -0.71238898])

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?

fzero reference

解决方案

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屋!

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