我是一個新手,正在練習如何使用pylab和matplot lib等。
不知為何,我無法在pylab/matplotlib中繪制這個簡單的支鏈sin(x)函式。
from math import sin
import pylab as plb
def f(x)。
if sin(x) > 0:
return sin(x)
else:
return 0.
x = plb.linspace(-4,4, 10000)
plb.plot(x,f(x))
plb.show()
當我運行該程式時,輸出的錯誤如下:
Traceback (most recent call last):
檔案 "C:/Users/...plot.py", line 12, in <module>
plb.plot(x,f(x))
檔案 "C:/Users/......plot.py", line 5, in f
if sin(x) > 0:
TypeError: 只有大小1陣列可以被轉換為Python標量
有誰能幫助我嗎?
uj5u.com熱心網友回復:
數學模塊中內置的正弦函式只接受一個標量值。你可以使用numpy正弦來完成你的繪圖,因為它接受一個陣列。
import numpy as np
import pylab as plb
def f(x)。
sine_ = np.sin(x)
sine_[sine_< 0] =0
return sine_
x = plb.linspace(-4,4, 10000)
plb.plot(x,f(x))
plb.show()
輸出結果如下所示:
[
]
然而,正如Trenton McKinney所指出的,這個答案指出,不再推薦使用pylab。因此,使用matplotlib.pyplot的替代解決方案如下:
import numpy as np
import matplotlib.pyplot as plt
def f(x)。
sine_ = np.sin(x)
sine_[sine_< 0] =0
return sine_
x = np.linspace(-4,4, 10000)
plt.plot(x,f(x))
plt.show()
輸出結果與上面的圖片相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328931.html
標籤:
上一篇:在R中對2個串列進行迭代
