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

 

 

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

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

Rounds x up to its nearest integer and returns that integer.

>>> import math

>>> math.ceil(2.2)
3

math.floor(x)

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

Rounds x down to its nearest integer and returns that integer.

>>> import math

>>> math.floor(3.6)
3

math.fabs(x)

返回 x 的绝对值

Returns the absolute value for x as a float.

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

posted @ 2022-01-17 21:25  emanlee  阅读(1549)  评论(0编辑  收藏  举报