Ⅰ 鐢ㄤ笁鍒嗘硶奼傛瀬鍊紁ython
涓夊垎娉曢氬父鐢ㄤ簬奼傚嚱鏁板湪鍗曞嘲鍖洪棿涓婄殑鏋佸箋傚叾鍩烘湰鎬濇兂鏄鍦ㄥ尯闂寸殑涓鐐瑰勯夋嫨涓鐐逛綔涓虹鐐癸紝濡傛灉璇ョ偣宸﹁竟鐨勫嚱鏁板煎皬浜庡彸杈圭殑鍑芥暟鍊礆紝鍒欏湪宸﹀崐鍖洪棿鍐呴夋嫨涓涓鏂扮殑涓鐐癸紝鍚﹀垯鍦ㄥ彸鍗婂尯闂村唴閫夋嫨涓涓鏂扮殑涓鐐廣傞噸澶嶈繖涓榪囩▼錛岀洿鍒板尯闂磋凍澶熷皬錛屽嵆鍙寰楀埌鍗曞嘲鍖洪棿涓婄殑鏋佸艱繎浼煎箋
涓嬮潰鏄涓涓浣跨敤涓夊垎娉曟眰鍑芥暟鏋佸肩殑python浠g爜紺轟緥錛
def f(x):
return -(x-1)**2 + 2
def ternary_search(left, right, eps):
while right - left > eps:
left_third = left + (right - left) / 3
right_third = right - (right - left) / 3
if f(left_third) < f(right_third):
left = left_third
else:
right = right_third
return (left + right) / 2
xmin = ternary_search(0, 2, 0.0001)
print("xmin:", xmin)
print("f(xmin):", f(xmin))
涓婅堪浠g爜涓錛屽嚱鏁癴瀹氫箟浜嗛渶瑕佹眰鏋佸肩殑鍑芥暟錛宼ernary_search鍑芥暟瀹炵幇浜嗕笁鍒嗘硶錛屽苟鎺ュ彈涓変釜鍙傛暟錛氬乏絝鐐筶eft銆佸彸絝鐐箁ight鍜岀簿搴eps銆傚叾涓錛宭eft鍜宺ight瀹氫箟浜嗗崟宄板尯闂寸殑宸﹀彸絝鐐癸紝eps鐢ㄤ簬鎸囧畾鏋佸肩殑榪戜技綺懼害銆倀ernary_search鍑芥暟閫氳繃涓嶆柇緙╁皬鍖洪棿鐨勫ぇ灝忥紝鏈緇堣繑鍥炲尯闂寸殑涓鐐癸紝璇ヤ腑鐐瑰彲浠ヨ繎浼艱嗕負鍑芥暟鐨勬瀬鍊箋傚湪鏈紺轟緥涓錛屾垜浠閫氳繃璋冪敤ternary_search鍑芥暟奼傚嚭鍑芥暟f鍦╗0, 2]鍖洪棿鍐呯殑鏋佸箋
闇瑕佹敞鎰忕殑鏄錛屼嬌鐢ㄤ笁鍒嗘硶奼傚嚱鏁版瀬鍊奸渶瑕佷繚璇佸嚱鏁板湪鍗曞嘲鍖洪棿涓婅繛緇涓斿崟璋冩у彉鍖栵紝鍚﹀垯鍙鑳芥棤娉曞緱鍒版g『緇撴灉銆
Ⅱ plotly奼傚嚱鏁版瀬鍊
瑕佺敤 Plotly 奼傚嚱鏁扮殑鏋佸礆紝闇瑕佸仛浠ヤ笅鍑犱釜姝ラわ細
1. 瀹氫箟鍑芥暟錛氬湪 Python 涓瀹氫箟浣犺佹眰鏋佸肩殑鍑芥暟錛屽苟浣跨敤 NumPy 涓鐨 linspace() 鍑芥暟鍒涘緩涓涓鍖呭惈璇ュ嚱鏁版墍闇鍙橀噺鍊肩殑鏁扮粍錛屼緥濡傦細
```pythonimport numpy as npdef f(x):
return np.sin(x) * np.exp(-.1*x)
x = np.linspace(,10,100)
y = f(x)
```
2. 緇樺埗鍥懼儚錛氫嬌鐢 Plotly 涓鐨 graph_objs 妯″潡鍒涘緩涓涓鏂扮殑 Figure 瀵硅薄錛岀劧鍚庢坊鍔犱竴涓 scatter trace 鏉ヨ〃紺哄嚱鏁板浘鍍忋備緥濡傦細
```pythonimport plotly.graph_objs as gofig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
```
3. 奼傛瀬鍊礆細浣跨敤 NumPy 涓鐨 argmax() 鍜 argmin() 鍑芥暟鏉ユ壘鍒板嚱鏁扮殑鏈澶у拰鏈灝忓肩殑緔㈠紩錛岀劧鍚庝嬌鐢ㄨ繖浜涚儲寮曟潵紜瀹氭瀬鍊肩殑鍏蜂綋浣嶇疆銆備緥濡傦細
```pythonx_max = x[np.argmax(y)]
y_max = np.max(y)
x_min = x[np.argmin(y)]
y_min = np.min(y)
```
4. 娣誨姞杞ㄨ抗錛氫嬌鐢 Plotly 涓鐨 add_trace() 鏂規硶灝嗘瀬鍊艱建榪規坊鍔犲埌鍥懼艦涓銆備緥濡傦細
```pythonfig.add_trace(go.Scatter(x=[x_max], y=[y_max], mode='markers', marker=dict(color='red', size=10)))
fig.add_trace(go.Scatter(x=[x_min], y=[y_min], mode='markers', marker=dict(color='green', size=10)))
```
瀹屾暣浠g爜濡備笅錛
```pythonimport numpy as npimport plotly.graph_objs as godef f(x):
return np.sin(x) * np.exp(-.1*x)
x = np.linspace(,10,100)
y = f(x)
x_max = x[np.argmax(y)]
y_max = np.max(y)
x_min = x[np.argmin(y)]
y_min = np.min(y)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
fig.add_trace(go.Scatter(x=[x_max], y=[y_max], mode='markers', marker=dict(color='red', size=10)))
fig.add_trace(go.Scatter(x=[x_min], y=[y_min], mode='markers', marker=dict(color='green', size=10)))
fig.show()
```
鎵ц岃ヤ唬鐮佸皢鐢熸垚涓涓 Plotly 鍥懼艦錛屽叾涓鍖呭惈浣犺佹眰鏋佸肩殑鍑芥暟鍥懼儚鍜屾瀬澶у煎拰鏋佸皬鍊肩殑鏍囪般
Ⅲ python 尋找曲線的峰值 谷值
a=[x,x,x,x,x,x,x]
h=[]
l=[]
foriinrange(1,len(a)-1):
if(a[i-1]<a[i]anda[i+1]<a[i]):
h.append(a[i])
elif(a[i-1]>a[i]anda[i+1]>a[i]):
l.append(a[i])
if(len(h)==0):
h.append(max(a))
if(len(l)==0):
l.append(min(a[a.index(max(a)):]))
printh
printl