DAY 7
0
AI & Data

## Day 7 : 當方程組無法用手算怎麼辦 -- 數值分析

，令，求x，這樣複雜的函數很難用手算，求得一個解析解。此時，可以透過牛頓法來求得的值。

### 牛頓法

x(n) = n次迭代後的根的近似解
N = 迭代次數
Pseudo code:
For n = 1~ N:

end
Python

``````# 目標函數
def func(c, x):
return 200*c*math.exp(c*x)*(0.65 - 0.01*x) - 2*math.exp(c*x)-0.45

# 目標函數的一次導數
def der_func(c, x, h=0.01):
return (func(c, x+h) - func(c, x)) / h

N = 100               # 迭代次數
initial_param = 0.0   # 初始值
final_param = 0.0     # 終值
diff = 10e5           # 差異
c=0.025               # 參數
cnt = 0               # 達標次數
error = []            # 迭代過程差異的紀錄

while (abs(diff) >= 10e-5) and (cnt <= N):
f = func(c, initial_param)
diff_f = der_func(c, initial_param)
final_param = initial_param - (f/diff_f)
diff = final_param - initial_param
error.append(abs(diff))
initial_param = final_param
cnt += 1

print(final_param, cnt)
``````

### 隨機搜尋法

Python

``````def func(c, x):
return 200*c*math.exp(c*x)*(0.65 - 0.01*x) - 2*math.exp(c*x)-0.45

min_y = 10e5
N = 1000
threshold = 10e-5
c=0.025
final_x = 0

for i in range(N):
approx_x = random.uniform(10, 30)
approx_y = func(c, approx_x)

if abs(approx_y) < min_y:
min_y = abs(approx_y)
final_x = approx_x

print(final_x, min_y)
``````