微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python入门示例系列09 Python数学运算

 

Python中的各种进制

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

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

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


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

>>> bin(10)   @H_404_12@#@H_404_12@ 十进制转换为二进制 将十进制 decimal system 转换成二进制 binary system
'0b1010'
>>> bin(0b11)  @H_404_12@#@H_404_12@ 二进制转化为二进制
'0b11'
>>> bin(0o23)  @H_404_12@#@H_404_12@ 八进制转换为二进制
'0b10011'
>>> bin(0x2a)  @H_404_12@#@H_404_12@ 十六进制转换为二进制
'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 b / a 输出结果 2.0
% 取模 - 返回除法的余数 b % a 输出结果 0
** 幂 - 返回x的y次幂 a**b 为1的2次方, 输出结果 1
// 取整除 - 返回商的整数部分(向下取整
>>> 9//2
4
>>> -9//2
-5

 

示例:

import time
currentTime = time.time( )         @H_404_12@#@H_404_12@ Get current time@H_404_12@
#@H_404_12@ Obtain the total seconds since midnight, Jan 1, 1970
totalSeconds = int ( currentTime )
@H_404_12@#@H_404_12@ Get the current second
currentSecond = totalSeconds % 60
@H_404_12@#@H_404_12@ Obtain the total minutes
totalMinutes = totalSeconds // 60
@H_404_12@#@H_404_12@ Compute the current minute in the hour
currentMinute = totalMinutes % 60
@H_404_12@#@H_404_12@ Obtain the total hours
totalHours = totalMinutes // 60
@H_404_12@#@H_404_12@ Compute the current hour
currentHour = totalHours % 24
@H_404_12@#@H_404_12@ display results
print("Current time is",currentHour,":",currentMinute,":",currentSecond,"GMT")

 

常用的数学函数math):

函数 描述 实例
math.ceil(x) 返回 >= x 的最小整数 (int) >>> math.ceil(2.2)
3
math.floor(x) 返回 <= x 的最大整数 (int) >>> math.floor(3.6)
3
math.fabs(x) 返回 x 的绝对值 >>> math.fabs(-2)
2.0

函数

 

函数 描述 实例
math.pow(x, y) 返回 x 的 y 次幂(乘方)。与内置的 ** 运算符不同,math.pow() 将其两个参数都转换为 float 类型。使用 ** 或内置的 pow() 函数计算精确的整数幂。 >>> math.pow(2, 3)
8.0
>>> math.pow(2, 3)
8
math.sqrt((x) 返回 x 的平方根 (square root)

 >>> math.sqrt(4)

2

round(a,b)

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐