Python学习:数学运算教程

一.Python中的各种进制

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

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

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

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

>>> bin(10)   # 十进制转换为二进制 将十进制 decimal system 转换成二进制 binary system
'0b1010'
>>> bin(0b11)  # 二进制转化为二进制
'0b11'
>>> bin(0o23)  # 八进制转换为二进制
'0b10011'
>>> bin(0x2a)  # 十六进制转换为二进制
'0b101010'

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

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

print(oct(10))

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

print(hex(10))

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

intfloatcomplex
100.02+3j
-100.205+6J
0b11-90.4.53e-7j
0o26032.3e+18.876j
0x6970.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除以yb / 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() 函数计算精确的整数幂。

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> 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)

>>>round(4.555,2)

>>>round(5.555,2)
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值