利用 CoCalc 網站的 ChatGPT 對話窗來算數學

圖片
CoCalc 網站 提供了線上計算的平台環境,作者致力於發展用電腦做數學運算,開發了 SageMath 這種數學計算程式。 在 CoCalc 網站中,除了提供 SageMath 的計算,也提供了 Python, R 等等計算環境。 登入 CoCalc 網站後,在首頁會有 Extensive ChatGPT Integration 的對話視窗,整合了 ChatGPT 與網站數學運算的功能。 我們也可以利用這個 ChatGPT 視窗,輸入文字提示指令來得到如何做數學計算。 例如輸入: “用 Python 畫出 y = x^2 + 3x + 1 = 0 的函數圖形。” 網站就會生成 Python 程式碼: import numpy as np import matplotlib . pyplot as plt x = np . linspace ( - 10 , 10 , 100 ) # Generate 100 points between -10 and 10 y = x ** 2 + 3 * x + 1 # Calculate y values plt . plot ( x , y ) plt . xlabel ( 'x' ) plt . ylabel ( 'y' ) plt . title ( 'Graph of y = x^2 + 3x + 1' ) plt . grid ( True ) plt . show ( ) SageMath 本身也是一個功能強大的數學計算軟體。我們來使用看看。在 CoCalc 的 ChatGPT 對話窗輸入: “用 SageMath 畫出 y = x^2 + 3x + 1 的函數圖形,並且求 x^2 + 3x + 1 = 0 的解。” 得到 SageMath 的程式碼,並且執行它: # Plot the graph of y = x^2 + 3x + 1 f ( x ) = x ^ 2 + 3 * x + 1 plot ( f , - 5 , 5 , ymin = - 5 , ymax = 20 , color = 'blue' ) # Solve the equati

Python 常用的數學函數

Python 常用的數學函數列表

函數 描述 範例
math.sqrt(x) 開平方根 math.sqrt(16)4.0
math.pow(x, y) (x) 的 (y) 次方 math.pow(2, 3)8.0
math.sin(x) 正弦函數 math.sin(math.pi / 2)1.0
math.cos(x) 餘弦函數 math.cos(math.pi)-1.0
math.tan(x) 正切函數 math.tan(math.pi / 4)1.0
math.asin(x) 反正弦函數 math.asin(1)π/2
math.acos(x) 反餘弦函數 math.acos(1)0.0
math.atan(x) 反正切函數 math.atan(1)π/4
math.exp(x) (e) 的 (x) 次方 math.exp(1)2.71828...
math.log(x) 自然對數(以 (e) 為底) math.log(math.e)1.0
math.log10(x) 以 10 為底的對數 math.log10(100)2.0
math.factorial(x) (x) 的階乘 math.factorial(5)120

請注意,使用這些函數之前,需要在 Python 程式中引入 math 模組,即在程式的開頭加入 import math

import math

之後就可以使用這些函數。例如,要計算 2 的 4 次方:

math.pow(2, 4)
16.0

圓周率 π 在這裡是用 math.pi 表示:

math.pi
3.141592653589793

自然對數的底數 e 是用 math.e 表示:

math.e
2.718281828459045

三角函數的計算時,要注意角度是要用弧度 (radian, rad) 計算,不是用 (degree)。弧度的數學定義是:一個圓心角的弧度數等於該角所截取圓弧的長度與圓的半徑的比值。

一個半徑為 r 的圓形,圓心角為 180° 時,對應的圓弧長度是 π r。也就是說,180° 相等於弧度 π rad

\(\frac{\pi}{2}rad = 90^\circ\)

\(\frac{\pi}{3}rad = 60^\circ\)

\(\frac{\pi}{4}rad = 45^\circ\)

\(\frac{\pi}{6}rad = 30^\circ\)

例如,要計算 sin(30°) 的值,必需要以 sin(π/6) 來計算,輸入:

math.sin(math.pi / 6)
0.49999999999999994

有趣的是,計算出來的答案不是 0.5,而是近似值。這是因為 Python 程式是以浮點數來做數值計算,所以產生的值可能是近似值。這在程式運算中時常會出現,使用者要留意可能產生的細微誤差。由這個例子,也可以看出電腦和人腦的差別。

若要在弧度和度之間轉換,math 模組也提供了兩個函數方便轉換 radians()degrees()

# 將度轉為弧度
degrees = 90

radians = math.radians(degrees)

print(degrees, "度", "等於",  radians, "弧度")
90 度 等於 1.5707963267948966 弧度
# 將弧度轉換為度
radians = 1.5

degrees = math.degrees(radians)

print(radians, "弧度", "等於", degrees, "度")
1.5 弧度 等於 85.94366926962348 度

現在,您也可以試著用這些數學函數來做常見的計算了。

這個網誌中的熱門文章

在 Colab 筆記本裡呈現更美觀的數學式

用 Colab AI 生成程式碼解數學方程式

利用 CoCalc 網站的 ChatGPT 對話窗來算數學