2019年2月24日 星期日

Julia語言 EX2-1利用2分法求 x^3-4x+2 =0 在0.0到2.0之間的解

Julia語言 EX2-1利用2分法求 x^3-4x+2 =0 在0.0到2.0之間的解
================================
x^3-4x+2 =0 在0.0到2.0之間的解
================================

虛擬碼



Algorithm BiSect

    E0 : 初始化最小誤差 EPS,初始化上界 a,下界 b。

    E1 :  c = (a+b)  / 2

    E2 :  if abs ( f(c)  ) <= EPS ,演算法結束,傳回 c 值。

    E3 :  if ( f(c) * f(a) <= 0)   b = c;
            else  a = c;

    E4 :  goto E1

End Algorithm


程式

using Printf

#==============================================================
Arithmetic Operators
The following arithmetic operators are supported on all primitive numeric types:

Expression Name Description
+x unary plus the identity operation
-x unary minus maps values to their additive inverses
x + y binary plus performs addition
x - y binary minus performs subtraction
x * y times performs multiplication
x / y divide performs division
x ÷ y integer divide x / y, truncated to an integer
x \ y inverse divide equivalent to y / x
x ^ y power raises x to the yth power
x % y remainder equivalent to rem(x,y)
==============================================================#

function fx(x::Float64) # 原非線性方程式
    return (x^3 -4.0*x +2.0)
end

a=0.0
b=2.0
x=a
println(" i\t  x\t   f(x)");
i=1
while (x<=b)
    s=@sprintf("%2d\t%5.2f\t%10.5f",i,x,fx(x))
    println(s)
    x=x+0.1
    i+=1
end

輸出畫面
 i   x    f(x)
 1  0.00    2.00000
 2  0.10    1.60100
 3  0.20    1.20800
 4  0.30    0.82700
 5  0.40    0.46400
 6  0.50    0.12500
 7  0.60   -0.18400
 8  0.70   -0.45700
 9  0.80   -0.68800
10  0.90   -0.87100
11  1.00   -1.00000
12  1.10   -1.06900
13  1.20   -1.07200
14  1.30   -1.00300
15  1.40   -0.85600
16  1.50   -0.62500
17  1.60   -0.30400
18  1.70    0.11300
19  1.80    0.63200
20  1.90    1.25900

沒有留言:

張貼留言

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> &...