数学运算模块:Python3.7的math模块与cmath模块

数学运算模块:math与cmath

作者:Shawn
python3.7
文档:
https://docs.python.org/3/library/math.html
https://docs.python.org/3/library/cmath.html

math模块

  • 其实不起眼的math里加进去了很多黑科技。

常规部分

math.ceil(x)
  • 向上取整
>>> import math
>>> math.ceil(0.0)
0
>>> math.ceil(0.1)
1
>>> math.ceil(41.1)
42
math.copysign(x, y)
  • copy符号
  • 返回x的绝对值和y的符号(对不起,这是我和他的孩子)
>>> import math
>>> math.copysign(1, -0.0)
-1.0
>>> math.copysign(-1, 0.0)
1.0
>>> math.copysign(-1, -0.0)
-1.0
>>> math.copysign(1, 0)
1.0
math.fabs(x)
  • 返回绝对值
  • math.fabs()与内置函数abs()的区别:
    • fabs需要import math后才能调用,abs可以直接使用
    • abs可以用于复数而fabs不可以。
>>> math.fabs(-8)
8.0
>>> abs(-8)
8
>>> abs(1+1.0j)
1.4142135623730951
>>> math.fabs(1+1.0j)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    math.fabs(1+1.0j)
TypeError: can't convert complex to float
math.factorial(x)
  • 这个函数竟然可以返回x!
  • 2乘3竟然等于3!
  • (返回x的阶乘)
>>> math.factorial(3)
6
>>> math.factorial(10)
3628800
math.floor(x)
  • 向下取整
>>> math.floor(0.0)
0
>>> math.floor(0.1)
0
>>> math.floor(-0.1)
-1
>>> math.floor(42.9)
42
math.fmod(x, y)
  • 取模运算
  • 与路人运算符号%的区别:
    • fmod默认返回浮点数
    • 对于x、y符号一致时,%与fmod结果一致
    • 但x、y符号不一致时,结果不同
    • 详见取模运算
>>> 3%2
1
>>> 3%-2
-1
>>> -3%2
1
>>> 3.1%3
0.10000000000000009
>>> math.fmod(3, 2)
1.0
>>> math.fmod(3, -2)
1.0
>>> math.fmod(-3, 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值