网上有没有专门针对python的二分法?
例如,给定这些方程,我如何使用二分法求解它们?
x^3 = 9
3 * x^3 + x^2 = x + 5
cos^2x + 6 = x 发布于 2010-12-02 00:48:41
使用scipy.optimize.bisect
import scipy.optimize as optimize
import numpy as np
def func(x):
return np.cos(x)**2 + 6 - x
# 0<=cos(x)**2<=1, so the root has to be between x=6 and x=7
print(optimize.bisect(func, 6, 7))
# 6.77609231632optimize.bisect调用_zeros._bisect,这是用C实现的。
发布于 2020-07-29 13:12:17
这可能会对你有帮助!
import numpy as np
def fn(x):
# This the equation to find the root
return (x**3 - x - 1) #x**2 - x - 1
def find_root_interval():
for x in range(0, 1000):
if fn(x) < 0:
lower_interval = x
if fn(x+1) > 0:
higher_interval = x + 1
return lower_interval, higher_interval
return False
def bisection():
a,b = find_root_interval()
print("Interval: [{},{}]".format(a,b))
# Create a 1000 equally spaced values between interval
mid = 0
while True:
prev_mid = mid
mid = (a+b)/2
print("Mid value: "+str(mid))
# 0.0005 is set as the error range
if abs(mid-prev_mid) < 0.0005:
return mid
elif fn(mid) > 0:
b = mid
else:
a = mid
root = bisection()
print(root)https://stackoverflow.com/questions/4326667
复制相似问题