簡體   English   中英

嘗試使用 plot python 中的三角形 function 使用 ZA3CBC3F9D0CE2F2C1554E1B671D7

[英]Trying to plot the triangular function in python using arrays

我的問題是:編寫三角形 function 的矢量化版本。 function 應該將 NumPy 數組作為輸入並返回向量化數組。 您還應該使用 matplot 顯示三角形。

我正在努力矢量化 function

t(x) = 0, x < 0; x, 0 <= x <1; 2-x, 1 <= x < 2, 0, x >= 2 t(x) = 0, x < 0; x, 0 <= x <1; 2-x, 1 <= x < 2, 0, x >= 2

甚至不確定如何將其放入數組 tbh

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
def triangle (x):
    return np.where(x<0, 0, 1)
plt.ylim(0,1)
plt.xlim(0,8)
plt.show(x)

據我了解,這個想法是不使用if語句。

import numpy as np
import matplotlib.pyplot as plt

def my_fun(x):
    y = np.zeros_like(x)
    mask = (x >= 0) & (x < 1)
    y[mask] = x[mask]
    mask = (x >= 1) & (x < 2)
    y[mask] = 2. - x[mask]
    return y

x = np.random.rand(1000) * 5 - 1.
y = my_fun(x)

plt.plot(x, y, 'o')
plt.show()

我正在對已修改的 select 值使用掩碼。 還必須屏蔽x值,以便正確完成計算。 請注意plt.show()通常不使用 arguments 並且只顯示您之前繪制的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM