2019年1月19日 星期六

例題2-7 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根

例題2-7
已知方程式 e^x + x^-2 + 2 cosx -6
利用正割法(secant method) 採用誤差0.00001 找出f(x)=0的根


# Program to find root of an equations using secant method
from math import *


def f_cal(x):
    # we are taking equation as e^x + x^-2 + 2 cosx -6
    f = exp(x)+1/pow(x,2) + 2*cos(x) - 6.0
    return f

def secant(x1,x2,E):
    n = 0.0
    xm=0.0
    x0=0.0
    c=0.0
   
    if (f_cal(x1) * f_cal(x2) > 0):
        print( "Can not find a root in the given inteval")
    else:
        # calculate the intermediate value
        x0= (x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))
        print("(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))",round(x0,6),'\n')     
        # check if x0 is root of equation or not
        c = f_cal(x1) * f_cal(x0)
        # update the value of interval
        x1 = x2
        x2 = x0
        # update number of iteration
        n=n+1
           
        #if x0 is the root of equation then break the loop
        if (c == 0):
            exit()
        xm = (x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))
# repeat the loop until the convergence

        while (abs(xm - x0) >= E): #// repeat the loop
            # calculate the intermediate value
            x0= (x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))
            print("(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))",round(x0,6),'\n')
            # check if x0 is root of equation or not
            c = f_cal(x1) * f_cal(x0)
            # update the value of interval
            x1 = x2
            x2 = x0
            # update number of iteration
            n=n+1
           
            #if x0 is the root of equation then break the loop
            if (c == 0):
                break

            xm = (x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))
            print("(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1))",round(xm,6),'\n')
    # repeat the loop until the convergence

   
        print("Root of the given equation= {%8.5f}" %(x0))
        print("No. of iterations = {%5d}" %(n))


#initializing the values
#x1 = 0.0
#x2 = 1.0
x1=1.8
x2=2.0
E = 0.00001
secant(x1, x2, E)


========= RESTART: F:\2018-09勤益科大數值分析\數值分析\PYTHON\EX2-7.py =============
(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1)) 1.821291 

(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1)) 1.824439 

(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1)) 1.824979 

(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1)) 1.824979 

(x1 * f_cal(x2) - x2 * f_cal(x1)) / (f_cal(x2) - f_cal(x1)) 1.824977 

Root of the given equation= { 1.82498}
No. of iterations = {    3}
>>>

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...