python2 浮点数操作常见“陷阱”
2016-06-09 00:08
549 查看
(1)刚接触Python2进行除法运算可能会感动很奇怪:
思考了一会,你可能会这样改进
这里给你推荐函数round(x,n)
(2)请思考下面这段两端代码会输出什么:
#coding=utf-8
i = 1
k = 1
while round(i,1) != 1.5:
i += 0.1
k += 1
if k == 10:
print 'See you'
break
print 'The value of i is {0}'.format(i)
如果得出正确答案,恭喜你!else,请看下面比较具体的解答(注:截图来自《Python核心编程》):
>>> 3/2 1 >>> 10/3 3 >>>结果为整数?
思考了一会,你可能会这样改进
>>> float(3)/2 1.5 >>> float(10)/3 3.3333333333333335 >>>恩恩,这样的确解决了少数部分被"抛弃"的现象,但float(10)/3这样的精度可能不是你希望的。
这里给你推荐函数round(x,n)
>>> help(round) Help on built-in function round in module __builtin__: round(...) round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. >>>
(2)请思考下面这段两端代码会输出什么:
#coding=utf-8 i = 1 k = 1 while i != 1.5: i += 0.1 k += 1 if k == 10: print 'See you' break print 'The value of i is {0}'.format(i)
#coding=utf-8
i = 1
k = 1
while round(i,1) != 1.5:
i += 0.1
k += 1
if k == 10:
print 'See you'
break
print 'The value of i is {0}'.format(i)
如果得出正确答案,恭喜你!else,请看下面比较具体的解答(注:截图来自《Python核心编程》):
相关文章推荐
- 开始使用Python
- Using Python to create UNIX command line tools
- Python实现两个list求交集,并集,差集的方法示例
- Python编程环境下的SSH远程操作
- Python3学习笔记03-基本数据类型、序列、运算及缩进和选择
- Python3学习笔记04-循环、函数、面向对象
- Python3学习笔记05-字典、文件输入输出、模块、函数参数传递
- Python3学习笔记06-循环设计、循环对象、函数对象、错误处理、动态类型
- python图像融合(基于PIL Image模块)
- python图像融合(基于PIL image库)
- 【随时更新】小菜梆子的Python Challenge 攻略过程
- Python pip install
- 利用python模拟分形生长树
- Python for 循环
- Python学习笔记(三)windows下安装theano
- python模块使用
- Python自然语言工具包(NLTK)入门
- Python学习笔记(三)windows下安装theano
- 机器学习笔记-FCM算法python实现
- Python全栈开发之9、面向对象、元类以及单例