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的根

'''
/* ex2-7.c Secant Method is similar to Newton-Raphson
 *  Method used for find solutions to f(x)=0 given
 *  initial approximations x0 and x1.
 */
 '''
from math import *
def f_fun(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

#define  PI  3.14159
TOL =  0.00001
MAX= 50
# f(x) =   (exp(x)+1/pow(2,x)+2*cos(x)-6)
i=2;
x0=1.8;
x1=2.0;
q0=f_fun(x0);
q1=f_fun(x1);
print ("i",'\t','xi','\t','f(x)','\n' )
print('===============================')
print('{%2d}\t{%10.6f}\t{%10.6f}\n' %(0,x0,q0) )
print('{%2d}\t{%10.6f}\t{%10.6f}\n' %(1,x1,q1) )

while(i<=MAX):
    x=x1-q1*(x1-x0)/(q1-q0);
    print('{%2d}\t{%10.6f}\t{%10.6f}\n' %(i,x,f_fun(x)) )
    if(abs(x-x1) < TOL):
        print('===============================')
        print("The Root={%10.6f} f({%10.6f})={%10.6f}\n"  %(x,x,f_fun(x)))
        exit(0);
    else:
        i=i+1
        x0=x1;
        q0=q1;
        x1=x;
        q1=f_fun(x);

if(i>MAX):
    print("Secant Method faileds!!!\n")


======== RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/EX2-7-1.py ============
i xi f(x) 

===============================
{ 0} {  1.800000} { -0.096115}

{ 1} {  2.000000} {  0.806762}

{ 2} {  1.821291} { -0.014468}

{ 3} {  1.824439} { -0.002118}

{ 4} {  1.824979} {  0.000007}

{ 5} {  1.824977} { -0.000000}

===============================
The Root={  1.824977} f({  1.824977})={ -0.000000}

>>> 

沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...