Python 学习笔记(五)常用函数

Python内建函数

  四舍五入: round()

  绝对值: abs()

 1 >>> round(1.543,2)   保留两位小数,四舍五入为1.54
 2 1.54
 3 >>> round(1.546,2)   保留两位小数,四舍五入为1.55
 4 1.55
 5 >>> round(-1.536,2) 
 6 -1.54
 7 >>> abs(5)  
 8 5
 9 >>> abs(-5)    绝对值为5
10 5

  math 模块 

 1 >>> import math   导入math模块
 2 >>> math.pi        math的pi函数
 3 3.141592653589793
 4 >>> dir(math)     利用dir 查看math中的函数
 5 ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
 6 >>> help(math.fabs)  利用help 查看函数的详细内容
 7 Help on built-in function fabs in module math:
 8 
 9 fabs(...)
10     fabs(x)
11 
12     Return the absolute value of the float x.   返回浮点数x的绝对值
13 
14 >>>
>>> math.sqrt(9)  计算开平方
3.0
>>> math.floor(3.14) 地板,将某一个位置之后的全部取消掉
3.0
>>> math.floor(3.66)
3.0
>>> math.fabs(2) 计算绝对值
2.0
>>> math.fmod(9,2) 计算余数
1.0

   解决浮点数运算问题Decimal

 1 >>> from decimal import Decimal  引入Decimal 模块
 2 >>> a = Decimal("0.1")
 3 >>> b = Decimal("0.8")
 4 >>> a + b
 5 Decimal('0.9')
 6 >>> from decimal import Decimal as D   as  别名
 7 >>> a = D("0.1")
 8 >>> b = D("0.8")
 9 >>> a + b
10 Decimal('0.9')
11 >>>

 

posted @ 2018-03-10 23:38  冰雪柔情的天空  阅读(222)  评论(0编辑  收藏  举报