Python入門示例系列09 Python數學運算


 

Python中的各種進制

一、二進制,八進制,十進制,十六進制的表示方法

在 python 的 IDLE 中輸入的不同進制的數值,直接轉化為十進制

>>> 0b10  # 以 0b 開頭表示的是二進制(b - Binary )/ ˈbaɪnəri /
2
>>> 0o10  # 以 0o 開頭表示的是八進制 (o - 字母歐 Octal) / ˈɒktl /
8
>>> 0x10  # 以 0x 開頭表示的是十六進制 (x - 字母埃克斯 Hexadecimal)/ ˌheksəˈdesɪml /
16
>>> 10    # 正常輸入表示的是十進制
10


二、將其他進制的數值轉換為二進制,使用函數 bin()

>>> bin(10)   # 十進制轉換為二進制 將十進制 decimal system 轉換成二進制 binary system
'0b1010'
>>> bin(0b11)  # 二進制轉化為二進制
'0b11'
>>> bin(0o23)  # 八進制轉換為二進制
'0b10011'
>>> bin(0x2a)  # 十六進制轉換為二進制
'0b101010'


三、轉為八進制使用 oct() 函數,轉為十六進制使用 hex()函數

將十進制 decimal system 轉換成八進制 Octal

print(oct(10))


將十進制decimal system轉換成十六進制 Hexadecimal

print(hex(10))

 

 

整數、浮點數、復數 數值類型示例

int float complex
10 0.0 2+3j
-100 .20 5+6J
0b11 -90. 4.53e-7j
0o260 32.3e+18 .876j
0x69 70.2E-12 -.6545+0J

Python 支持復數,復數由實數部分和虛數部分構成,可以用a + bj, 或者 complex(a,b) 表示, 復數的實部 a 和虛部 b 都是浮點型。

 

算術運算

以下假設變量: a=1,b=2

運算符 描述 實例
+ 加 - 兩個對象相加 a + b 輸出結果 3
- 減 - 得到負數或是一個數減去另一個數 a - b 輸出結果 -1
* 乘 - 兩個數相乘或是返回一個被重復若干次的字符串 a * b 輸出結果 2
/ 除 - 示例:x/y 表示 x除以y b / a 輸出結果 2.0
% 取模 - 示例:x%y 表示 x除以y的余數 b % a 輸出結果 0
** 冪 - 示例:x**y  表示 x的y次冪 a**b 為1的2次方, 輸出結果 1
// 取整除 - 示例:x//y 表示 x除以y的商的整數部分(向下取整
>>> 9//2 4 >>> -9//2 -5

 

示例:

import time
currentTime = time.time( )         # Get current time
# Obtain the total seconds since midnight, Jan 1, 1970
totalSeconds = int ( currentTime )
# Get the current second
currentSecond = totalSeconds % 60
# Obtain the total minutes
totalMinutes = totalSeconds // 60
# Compute the current minute in the hour
currentMinute = totalMinutes % 60
# Obtain the total hours
totalHours = totalMinutes // 60
# Compute the current hour
currentHour = totalHours % 24
# Display results
print("Current time is",currentHour,":",currentMinute,":",currentSecond,"GMT") ##
##格林尼治標准時間(舊譯格林威治平均時間或格林威治標准時間;英語:Greenwich Mean Time,GMT)

 

常用的數學函數(math):

函數 描述 實例
math.ceil(x) 返回 >= x 的最小整數 (int)

>>> import math

>>> math.ceil(2.2)
3

math.floor(x) 返回 <= x 的最大整數 (int)

>>> import math

>>> math.floor(3.6)
3

math.fabs(x) 返回 x 的絕對值

>>> import math

>>> math.fabs(-2)
2.0

函數

 

函數 描述 實例
math.pow(x, y)

返回 x 的 y 次冪(乘方)。與內置的 ** 運算符不同,

math.pow() 將其兩個參數都轉換為 float 類型。

使用 ** 或內置的 pow() 函數計算精確的整數冪。

>>> import math
>>> math.pow(2,3)
8.0
>>> 2**3
8
math.sqrt((x) 返回 x 的平方根 (square root)

 >>> import math

>>> math.sqrt(4)

2

round(a,b)

四舍五入精確到小數點的具體位數 round(a,b)

round(a,b), a是一個帶有小數的數字,b是指需要精確到小數點后幾位。

注意,round(a,b)不需要調用數學函數庫。

round函數的詳細解釋:Python 中的round函數

>>>round(3.555,2)

3.56

>>>round(4.555,2)

4.55

>>>round(5.555,2)

5.55

 

 

REF

https://www.runoob.com/python3/python3-data-type.html

https://www.runoob.com/python/python-operators.html#ysf1

https://www.cnblogs.com/jinian1002/p/9583410.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM