加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

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

发布时间:2023-04-11 11:17:24 所属栏目:教程 来源:
导读:Python中的各种进制
一、二进制,八进制,十进制,十六进制的表示方法

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

>>> 0b10 # 以 0b 开头表示的是二进制(b - Binary )
2
>>> 0o10 #
Python中的各种进制
一、二进制,八进制,十进制,十六进制的表示方法

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

>>> 0b10  # 以 0b 开头表示的是二进制(b - Binary )
2
>>> 0o10  # 以 0o 开头表示的是八进制 (o - 字母欧 Octal)
8
>>> 0x10  # 以 0x 开头表示的是十六进制 (x - 字母埃克斯 Hexadecimal)
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    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( )         # 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")
 
常用的数学函数(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

 

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章