Python - abs vs fabs
2016-01-14 14:09
507 查看
abs(-5) Second import math How do these methods differ? python
| |||
add a comment |
3 Answers
activeoldestvotesup vote59down voteaccepted | math.fabs()converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float. In addition to floats, abs()also works with integers and complex numbers. Its return type depends on the type of its argument. In [7]: type(abs(-2)) Out[7]: int In [8]: type(abs(-2.0)) Out[8]: float In [9]: type(abs(3+4j)) Out[9]: float In [10]: type(math.fabs(-2)) Out[10]: float In [11]: type(math.fabs(-2.0)) Out[11]: float In [12]: type(math.fabs(3+4j)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/alexei/<ipython-input-12-8368761369da> in <module>() ----> 1 type(math.fabs(3+4j)) TypeError: can't convert complex to float
| ||||||||||||||||
a comment |
up vote4down vote | Edit: as @aix suggested, a better (more fair) way to compare the speed difference:In [1]: %timeit abs(5) So it seems abs()only has slight speed advantage over fabs()for integers. For floats, abs()and fabs()demonstrate similar speed. In addition to what @aix has said, one more thing to consider is the speed difference: In [1]: %timeit abs(-5)10000000 loops, best of 3: 102 ns per loop So abs()is faster than math.fabs().
| ||||||||||||||||||||
|
相关文章推荐
- Python之路【第二篇】:Python基础(二)
- python基础之字符串
- 【转】Python装饰器与面向切面编程
- 第6课时:python之常用操作符
- python 二维码
- python 字典
- 第1课时 python 入门
- python 验证码
- 效率对比:Spark的Scala API与Python API(利用PageRank)
- Python图形界面开发初步 5
- Python图形界面开发初步 4
- python核心编程-正则表达式-产生测试数据
- python2编码总结(转)
- Python图形界面开发初步 3
- Python 基础 - 随机列表最大的两个值
- Python 基础 - 随机列表的交集
- python:解析js中常见的 不带引号的key的 json
- Python编程(四):两个实用的Python的装饰器
- 【python】网页内容抓取遭遇乱码问题
- Python 基础 - 对文本的处理