熱門文章

2018年6月18日 星期一

Android 手機上的 Python IDE: Pydroid 3

Android 手機上的 Python IDE: Pydroid 3

日期:2018/6/18


今天在 Google Play 上找到一個好玩的東西,名為 Pydroid 3 的 Python IDE,看起來評價不錯,就下載來試試看,以下是下載連結:https://play.google.com/store/apps/details?id=ru.iiec.pydroid3&hl=zh_TW




2018年6月13日 星期三

使用 matplotlib 繪製函數及數據圖

使用 matplotlib 繪製函數及數據圖


日期:2018/6/13

繪製函數圖


我之前曾經用 Gnuplot 畫函數圖形,但自從學了 Python 以及 matplotlib 之後,就想要用 Python 來畫圖,下圖是 -4π ≤ x ≤ +4π 範圍內對應的 sin(x) 圖形,下方則是程式碼。



"""
 Python筆記: 2D曲線圖
 日期: 2018/6/13
 作者: 王一哲
"""
import numpy as np                                        # 引入科學計算函式庫
import matplotlib.pyplot as plt                           # 引入繪圖函式庫

xmin, xmax, num = -4*np.pi, 4*np.pi, 1000                 # 設定繪圖範圍、取點數
x = np.linspace(xmin, xmax, num)                          # 產生x
y = np.sin(x)                                             # 產生y

plt.figure(figsize = (8, 6), dpi = 100)                   # 設定圖片尺寸
plt.xlabel('x(rad)', fontsize = 16)                       # 設定坐標軸標籤
plt.ylabel('sin(x)', fontsize = 16)
plt.xticks(fontsize = 12)                                 # 設定坐標軸數字格式
plt.yticks(fontsize = 12)
plt.grid(color = 'red', linestyle = '--', linewidth = 1)  # 設定格線顏色、種類、寬度
plt.plot(x, y, color = 'blue', linewidth = 3)             # 繪圖並設定線條顏色、寬度
plt.savefig('plot_2D.svg')                                # 儲存圖片
plt.savefig('plot_2D.png')
plt.show()                                                # 顯示圖片


2018年6月5日 星期二

使用 with 開啟檔案並寫入內容

使用 with 開啟檔案並寫入內容
日期:2018/6/6



我在之前的 VPython 文章〈使用for迴圈計算水平抛射資料〉以及水平抛射〉當中,將程式產生的資料轉成字串存到文字檔中,但是當時使用的寫法很有可能會因為最後沒有關閉檔案而發生問題,之前的寫法如下:

file = open("data.txt", "w", encoding = "UTF-8")
file.write("h(m), t(s), R(m)\n")

for h in range(5, 51, 1):
......
    file.write(str(h) + "," + str(t) + "," + str(ball.pos.x + L/2) + "\n")

file.close() 



在 Python 裡有一個小技巧,使用 with 開啟檔案,就可以避免忘記關閉檔案造成的問題,寫法如下:

with open("data.txt", "w", encoding = "UTF-8") as file:
    file.write("h(m), t(s), R(m)\n")

for h in range(5, 51, 1):
......
    with open("data.txt", "a", encoding = "UTF-8") as file:
        file.write(str(h) + "," + str(t) + "," + str(ball.pos.x + L/2) + "\n")



順帶一提,昨天花了一點時間測式高亮度語法的外掛程式,我採用的外掛是 Prism ( https://prismjs.com/index.html ),詳細的作法是參考這篇文章完成的:〈[技術分享] 寫給會在部落格中撰寫程式碼的你 ─ 在網頁中嵌入高亮程式碼上色 (syntax highlighting)〉。我昨天在 Ubuntu 上用 Google Chrome 編輯版面設置,但是沒辦法顯示高亮度語法;今天改用 Windows 再按照相同的步驟編輯就成功了,原因不明。