假设函数如下:
f(x) = x * cos(x-4)
对于x = [-2.5, 2.5],此函数在f(0) = 0和f(-0.71238898) = 0处跨越0。
这是通过以下代码确定的:
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]使用fzero (或任何其他Python root finder)在一次调用中查找两个根的正确方法是什么?有没有不同的scipy函数可以做到这一点?
fzero reference
发布于 2012-10-25 02:44:48
定义您的函数,以便它可以接受标量或numpy数组作为参数:
>>> import numpy as np
>>> f = lambda x : x * np.cos(x-4)然后将一个参数向量传递给fsolve。
>>> x = np.array([0.0, -0.75])
>>> fsolve(f,x)
array([ 0. , -0.71238898])发布于 2012-10-25 02:54:30
我曾经为这个任务写过一个模块。它基于Numerical Methods in Engineering with Python by Jaan Kiusalaas一书中的第4.3章
import math
def rootsearch(f,a,b,dx):
x1 = a; f1 = f(a)
x2 = a + dx; f2 = f(x2)
while f1*f2 > 0.0:
if x1 >= b:
return None,None
x1 = x2; f1 = f2
x2 = x1 + dx; f2 = f(x2)
return x1,x2
def bisect(f,x1,x2,switch=0,epsilon=1.0e-9):
f1 = f(x1)
if f1 == 0.0:
return x1
f2 = f(x2)
if f2 == 0.0:
return x2
if f1*f2 > 0.0:
print('Root is not bracketed')
return None
n = int(math.ceil(math.log(abs(x2 - x1)/epsilon)/math.log(2.0)))
for i in range(n):
x3 = 0.5*(x1 + x2); f3 = f(x3)
if (switch == 1) and (abs(f3) >abs(f1)) and (abs(f3) > abs(f2)):
return None
if f3 == 0.0:
return x3
if f2*f3 < 0.0:
x1 = x3
f1 = f3
else:
x2 =x3
f2 = f3
return (x1 + x2)/2.0
def roots(f, a, b, eps=1e-6):
print ('The roots on the interval [%f, %f] are:' % (a,b))
while 1:
x1,x2 = rootsearch(f,a,b,eps)
if x1 != None:
a = x2
root = bisect(f,x1,x2,1)
if root != None:
pass
print (round(root,-int(math.log(eps, 10))))
else:
print ('\nDone')
break
f=lambda x:x*math.cos(x-4)
roots(f, -3, 3)roots在区间a,b中查找f的所有根。
发布于 2012-10-25 02:45:08
一般来说(除非你的函数属于某个特定的类),你不可能找到所有的全局解--这些方法通常从给定的起始点进行局部优化。
但是,您可以将math.cos()与numpy.cos()进行切换,这将使您的函数向量化,以便它可以一次求解多个值,例如fsolve(func,np.arange(-10,10,0.5))。
https://stackoverflow.com/questions/13054758
复制相似问题