利用 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

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

在 SymPy 做數學符號運算時,輸出的數學式預設是以文字或符號來表示。

例如,我們輸出以下的式子:

from sympy import *

# Define the variable
x = Symbol("x")

print(sqrt(x**2 - 5) / 3 )
sqrt(x**2 - 5)/3

在上面的輸出,Python 是以 sqrt() 代表平方根。

如果要以較直觀的數學式來呈現,可以用以下的方法,先將文字的數學式轉換成 LaTeX 格式,再以 Math() 產生較美觀的式子。

from sympy import *
from IPython.display import Math, display

# Define the variable
x = Symbol("x")

result = sqrt(x**2 - 5) / 3

# 將文字數學式轉換為 LaTeX 格式
result_latex = latex(result)

# 再以較美觀的數學式呈現
display(Math(result_latex))

\(\displaystyle \frac{\sqrt{x^{2} - 5}}{3}\)

我們也可以把它應用在用 solve() 計算的方程式的答案。

from sympy import *
from IPython.display import Math, display

# Define the variable
x = Symbol("x")

# Create the equation
equation = Eq(x**2 - 5*x + 8, 0)

# Solve the equation
solution = solve(equation, x)

print(solution)
[5/2 - sqrt(7)*I/2, 5/2 + sqrt(7)*I/2]

原本的解是用文字表示,我們可以把它用更美觀的格式呈現。

# 將解轉換為 LaTeX 格式
solution_latex = latex(solution)

# 再以較美觀的數學式呈現
display(Math(solution_latex))

\(\displaystyle \left[ \frac{5}{2} - \frac{\sqrt{7} i}{2}, \ \frac{5}{2} + \frac{\sqrt{7} i}{2}\right]\)

另一種方式,是用 solveset() 來計算方程式的解,所得到的結果也會直接以較直觀的格式呈現。

from sympy import *

# Define the variable
x = Symbol("x")

# Create the equation
equation = Eq(x**2 - 5*x + 8, 0)

solveset(equation, x)

\(\displaystyle \left\{\frac{5}{2} - \frac{\sqrt{7} i}{2}, \frac{5}{2} + \frac{\sqrt{7} i}{2}\right\}\)

這個網誌中的熱門文章

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

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