我有一个函数func(x)。我想知道func(x)-7=0的x。因为没有确切的答案,我认为minimize会是一个好主意。
from scipy.optimize import minimize
def func(x): # testing function which leads to the same behaviour
return (x * 5 + x * (1 - x) * (6-3*x) * 5)
def comp(x): # comparison function which should get zero
return abs(((func(x)) - 7))
x0 = 0.
x_real = minimize(comp, x0) # minimize comparison function to get x
print(x_real.x)最后一个print给了我[ 0.7851167]。下面的print...
print(comp(x_real.x))
print(comp(0.7851167))...leads到不同的输出:
[ 1.31290960e-08]
6.151420706146382e-09有人能给我解释一下这种行为吗?
发布于 2019-03-10 20:58:38
编辑:我想我理解错了你的问题。像在打印语句中那样对数字进行四舍五入显然会产生一些差异(这些差异非常小(在1e-9附近))。
为了找到所有的x,你应该应用一些全局解的方法,或者从不同的初始点开始寻找所有的局部最小值(如图所示)。
然而,这个方程有两个解。
def func(x): # testing function which leads to the same behaviour
return (x * 5 + x * (1 - x) * (6-3*x) * 5)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.1,1,100)
plt.plot(x, func(x)-7)
plt.plot(x, np.zeros(100))
plt.show()函数:

https://stackoverflow.com/questions/55078393
复制相似问题