我必须根据参数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))
最佳答案
如果使用 scipy.optimize.root
,则返回值包含x
,解决方案数组和和success
布尔标志。您需要过滤掉success
为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)
关于python - 在Python中找到函数x = a * sin(x)的所有根,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59824652/