2022年 11月 5日

Python学习:数学运算教程

一.Python中的各种进制

1、二进制,八进制,十进制,十六进制的表示方法

在 python 的 IDLE 中输入的不同进制的数值,直接转化为十进制

>>> 0b10  # 以 0b 开头表示的是二进制(b - Binary )
2
>>> 0o10  # 以 0o 开头表示的是八进制 (o - 字母欧 Octal)
8
>>> 0x10  # 以 0x 开头表示的是十六进制 (x - 字母埃克斯 Hexadecimal)
16
>>> 10    # 正常输入表示的是十进制
10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.、将其他进制的数值转换为二进制,使用函数 bin()

>>> bin(10)   # 十进制转换为二进制 将十进制 decimal system 转换成二进制 binary system
'0b1010'
>>> bin(0b11)  # 二进制转化为二进制
'0b11'
>>> bin(0o23)  # 八进制转换为二进制
'0b10011'
>>> bin(0x2a)  # 十六进制转换为二进制
'0b101010'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、转为八进制使用 oct() 函数,转为十六进制使用 hex()函数

将十进制 decimal system 转换成八进制 Octal

print(oct(10))
  • 1

将十进制decimal system转换成十六进制 Hexadecimal

print(hex(10))
  • 1

二.整数、浮点数、复数 数值类型示例

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 b / a 输出结果 2.0
% 取模 – 返回除法的余数 b % a 输出结果 0
** 幂 – 返回x的y次幂 a**b 为1的2次方, 输出结果 1

// 取整除 – 返回商的整数部分(向下取整)

>>> 9//2
4
>>> -9//2
-5
  • 1
  • 2
  • 3
  • 4

示例:

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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

常用的数学函数(math):

math.ceil(x)
返回 >= x 的最小整数 (int)

>>> math.ceil(2.2)
3
  • 1
  • 2

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

>>> math.floor(3.6)
3
  • 1
  • 2

math.fabs(x)
返回 x 的绝对值

>>> math.fabs(-2)
2.0
  • 1
  • 2

四.函数

math.pow(x, y)

返回 x 的 y 次幂(乘方)。

与内置的 ** 运算符不同,math.pow() 将其两个参数都转换为 float 类型。

使用 ** 或内置的 pow() 函数计算精确的整数幂。

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> math.pow(2, 3)
8.0
>>> math.pow(2, 3)
8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

math.sqrt((x)
返回 x 的平方根 (square root)

 >>> math.sqrt(4)

2
  • 1
  • 2
  • 3

round(a,b)

四舍五入精确到小数点的具体位数 round(a,b)

round(a,b), a是一个带有小数的数字,b是指需要精确到小数点后几位。

注意,round(a,b)不需要调用数学函数库。

>>>round(3.555,2)

>>>round(4.555,2)

>>>round(5.555,2)
  • 1
  • 2
  • 3
  • 4
  • 5