[Python基礎] [內建函式]數學相關的函式

2024/01/27閱讀時間約 4 分鐘

Python 提供了一系列內建函式,其中一部分涉及數學數學操作

以下是一些常用內建函式數學相關函式

基本數學運算:

abs(x) 返回 x 的絕對值。

result = abs(-5)
print(result) # 輸出: 5


max(iterable)min(iterable) 分別返回可迭代對象中的最大和最小值。

numbers = [1, 2, 3, 4, 5]
max_value = max(numbers)
min_value = min(numbers)
print(max_value, min_value) # 輸出: 5 1


sum(iterable) 返回可迭代對象中所有元素的總和。

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 輸出: 15


divmod(a, b) 返回包含商和餘數的元組 (a // b, a % b)

result = divmod(10, 3)
print(result) # 輸出: (3, 1)


round(x, n): 返回 x 四舍五入到 n 位小數的結果。

rounded_value = round(3.14159, 2)
print(rounded_value) # 輸出: 3.14


ceil(x) : 將小數點後方的數字,無條件進位到整數。

import math
pi = math.pi
print(math.ceil(pi)) # 4


次方和開方

pow(x, y) 返回 x 的 y 次方。

result = pow(2, 3)
print(result) # 輸出: 8


sqrt(x) 返回 x 的平方根。

import math

result = math.sqrt(25)
print(result) # 輸出: 5.0


數學常數:

math.pi 圓周率 π。

import math

print(math.pi) # 輸出: 3.141592653589793


math.e 自然數 e。

import math

print(math.e) # 輸出: 2.718281828459045


三角函數:

degrees(x)、math.radians(x) 

math.degrees(x) 將 x 弧度轉換為角度,math.radians(x) 將 x 角度轉換為弧度。

import math
print(math.radians(45)) # 0.7853981633974483 # 角度轉換為弧度
print(math.degrees(0.7853981633974483)) # 45.0 # 弧度轉換為角度


math.sin(x)分別返回 x 正弦

math.cos(x)分別返回 x餘弦

math.tan(x) 分別返回 x正切值

import math

# 將角度轉換為弧度
angle = math.radians(45)

# 計算正弦、餘弦和正切值
sin_value = math.sin(angle)
cos_value = math.cos(angle)
tan_value = math.tan(angle)

# 輸出結果
print("Sin(45 degrees):", sin_value) # 輸出 0.7071067811865476
print("Cos(45 degrees):", cos_value) # 輸出 0.7071067811865476
print("Tan(45 degrees):", tan_value) # 輸出 0.9999999999999999

在Python中,math.tan(45) 的實際計算結果是接近1的數字,但由於浮點數的表示限制,該結果可能會有極小的誤差。這是一種常見的浮點數精度問題。


如果需要更複雜的數學運算,可能需要使用科學計算庫,例如 NumPySciPy













49會員
88內容數
Python程式設計師,不是在學習就是在學習的路上
留言0
查看全部
發表第一個留言支持創作者!