Ⅰ 鐢ㄤ笁鍒嗘硶姹傛瀬鍊紁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