W01: 2/14 === ### `基本概念` >`print()`:函數 >`()`:內容為參數 >`=`:指定 >`x=9`:9指定給x變數 --- ### [Python數學運算符 (Python Operators)](https://www.w3schools.com/python/python_operators.asp) #### Python算術運算符 (Python Arithmetic Operators) 算術運算符與數值一起使用以執行常見的數學運算: | Operator | Name | Description | Example | | -------- | -------------- | ----------- | ------- | | `+` | Addition | 求和 | `x+y` | | `-` | Subtraction | 求差 | `x-y` | | `*` | Multiplication | 求積 | `x*y` | | `/` | Division | 求商 | `x/y` | | `%` | Modulus | 求餘 | `x%y` | | `**` | Exponentiation | 次方 | `x**y` | | `//` | Floor division | 整數商 | `x//y` | --- #### Python 賦值運算符 (Python Assignment Operators) 賦值運算符用於為變數賦值: | Operator | Example | Same as | | -------- | --------- | ------------ | | `=` | `x = 5` | `x = 5` | | `+=` | `x += 3` | `x = x + 3` | | `-=` | `x -= 3` | `x = x - 3` | | `*=` | `x *= 3` | `x = x * 3` | | `/=` | `x /= 3` | `x = x / 3` | | `%=` | `x %= 3` | `x = x % 3` | | `**=` | `x **= 3` | `x = x ** 3` | | `//=` | `x //= 3` | `x = x // 3` | --- #### Python 比較運算符 (Python Comparison Operators) | Operator | Name | Description | Example | | -------- | ------------------------ | ----------- | ------- | | `==` | Equal | 等於 | `x == y` | | `!=` | Not equal | 不等於 | `x != y` | | `>` | Greater than | 大於 | `x > y` | | `<` | Less than | 小於 | `x < y` | | `>=` | Greater than or equal to | 不小於 | `x >= y` | | `<=` | Less than or equal to | 不大於 | `x <= y` | --- #### Python 邏輯運算符 (Python Logical Operators) | Operator | Description | Example | | -------- | ---------------------------------- | ----------------------- | | `and` | 若兩式皆為真,則回報 True | `x < 5 and x < 10` | | `or` | 若兩式其一為真,則回報 True | `x < 5 or x < 4` | | `not` | 反轉結果,若結果為真,則回報 False | `not(x < 5 and x < 10)` | --- ### 範例:數學公式初體驗 以下範例的參考來源:https://acupun.site/lecture/python_math/index.htm#exp3_7 ``` #引用現成的模組 from sympy import symbols, Eq, solve x = symbols('x') #一元多項式,相乘,展開 f = poly((x+1)*(x+1)*(x+1)) print(f) display(f) #二元多項式 x,y = symbols('x y') f = poly('(x+2*y+3)**2') display(f) ``` ``` #Ex1:二元一次方程式聯立求解 from sympy import * x, y = symbols('x y') #二元一次聯立方程式 f1 = Eq(x + 2*y - 8, 0) f2 = Eq(2*x - y - 6, 0) solve((f1,f2),(x,y)) #求解兩條線的交叉點(solve(f1,f2)) p1 = None p1 = plot_implicit(f1,show=False) p2 = plot_implicit(f2,show=False) p1.extend(p2) p1.show() print('解二元一次聯立方程式=', solve((f1,f2),(x,y))) ``` ``` #Ex2:求微分,常見的幾類微積分函數基本公式 from sympy import * x=symbols('x') f = Function('f')(x) #一階導數(對x) = 一階微分(對x) = diff(函數, x) f = 1/x print('求 y=1/x的微分=', diff(f, x)) f = 3*x**2 + 2*x + 5 print('求 y=3*x^2 + 2*x + 5的微分=', diff(f, x)) #常見的幾類微積分基本公式 f = sin(x) print('求sin(x)的微分=', diff(f, x)) f = cos(x) print('求cos(x)的微分=', diff(f, x)) #標準指數e的微分 f = E**x print('求E**x的微分=', diff(f, x)) f = exp(x) print('求exp(x)的微分=', diff(f, x)) #自然對數e的微分 #自然對數 = ln() #10為底的對數 = log() f = ln(x) print('求自然對數ln(x)的微分=', diff(f, x)) #多項式的微分 #如果方程式有未知參數n,就必須要加上'' f = 'x**n' print('求x**n的微分=', diff(f, x)) f = x**5 print('求x**5的微分=', diff(f, x)) ```