2019年2月14日 星期四

習題2-4-b 請用Newton-Raphson 求方程式的根 取 ε =0.00001 (b) sin(x) - x +1 =0

習題2-4-b 請用Newton-Raphson 求方程式的根
取 ε =0.00001

(b) sin(x) - x +1 =0


Python 程式
'''
/* Pr2-4.py is used for solving nonlinear equation f(x)=0
 * based on Newton-Raphson Method with initial approximation
 * p0.
 */

 d sin(x) /dx = cos(x)

 '''
import math
Max=100
TOL=  0.00001
def f(x):
    return (math.sin(x)  -x + 1.0)

def  ff(x):
    return (math.cos(x) -1.0  )

i=1
x0=1.0
while(i<=Max):
    x=x0-f(x0)/ff(x0);
    print("%2d   %10.7f\n" %(i-1,x0))
    if(abs(x-x0) <TOL):
        print("Root=%10.7f , | x-x0 |=%10.7f\n" %(x,abs(x-x0)))
        break
   
    i=i+1
    x0=x

print("Newton-Raphson Method failed after %2d  iterations!!!\n" %(i))


輸出畫面

======== RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/pr2-4-b.py ===========
 0    1.0000000

 1    2.8304877

 2    2.0495552

 3    1.9386561

 4    1.9345690

Root= 1.9345632 , | x-x0 |= 0.0000058

Newton-Raphson Method failed after  5  iterations!!!

>>> 

沒有留言:

張貼留言

2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2

 2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2 AngularJS 實例 <!DOCTYPE html> <html> <head> &...