首页 > 解决方案 > 在 Python 中查找函数 x = a*sin(x) 的所有根

问题描述

我必须根据参数 a 找到解决方案的数量。在使用 scipy.optimize.root 数值求解方程时,我得到一些不是函数根的数字。例如对于 x = 7*sin(x),我得到数字 -7.71046524 和 7.71046524。我的代码是:

a = np.linspace(-5, 5)

def fun(x):
    return x - b*np.sin(x)

for i in a:
    solutions = []
    b = i
    c = abs(int(round(i)))
    for j in range(-c, c+1):
        y = root(fun, j)
        if (round(y.x[0], 3) not in solutions):
            solutions.append(round(y.x[0], 3))
    print(len(solutions))

标签: pythonroot

解决方案


如果使用scipy.optimize.root,则返回值包含x解决方案数组布尔success标志。您需要过滤掉任何结果 where successis False

import numpy as np
from scipy.optimize import root

a = np.linspace(-7, 7)

def fun(x):
    return x - b*np.sin(x)

for i in a:
    solutions = []
    b = i
    c = abs(int(round(i)))
    for j in range(-c, c+1):
        y = root(fun, j)
        if y.success and (round(y.x[0], 6) not in solutions):
            solutions.append(round(y.x[0], 3))
    print(i, solutions)

推荐阅读