首页 > 解决方案 > 使用 Python 在二分法中添加解决方案

问题描述

我正在使用 python 的二分法并尝试将答案附加到解决方案数组中。因为二分法仅适用于 1 个根。我不知道为什么我的答案没有附加。

import math
for i in range (0,3):
solutions = []
a=i
b=3
func = lambda x: math.sin(3*x) - math.cos(2*x)
def bisection(f,a,b,tol):

    fa = f(a)
    if abs(fa) < tol:
        return a
   
    fb = f(b)
    if abs(fb) < tol:
        return b
    
    
    for _ in range (100):
        c=(a+b)/2
        fc=f(c)
        
        if fc == tol:
            break 
        if fa*fc>0:
            a, fa = c, fc
        if fa*fc<0:
            b, fb = c, fc
    
    return c
   
ans = bisection(func,a,b,1e-10)
solutions.append(ans)
print("The solution of the equation: ",solutions)

标签: python

解决方案


推荐阅读