数字精度

silentwins 2016-03-22 03:01:00
看起来以前的版本输入0.1会返回0.1000000000000001,需要精度就要引入decimal
现在用2.7都是返回0.1了

中间做了什么修改?现在还有没有float和decimal之分?还是它们自动转换了?

谢谢!

...全文
118 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
silentwins 2016-03-24
  • 打赏
  • 举报
回复
解释得很好,谢谢!
0.1000000000000000055511151231257827021181583404541015625 == 0.1
True

a = 0.1000000000000000055511151231257827021181583404541015625
print a
0.1
panghuhu250 2016-03-22
  • 打赏
  • 举报
回复
恐怕还是没变. 0.1的后面还是有尾数.
wind% python3
Python 3.5.1+ (default, Jan 13 2016, 15:09:18) 
[GCC 5.3.1 20160101] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> format(0.1, ".20f")
'0.10000000000000000555'
只是python显示浮点数的方式变了.python3的文档说:
引用
Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers 0.1 and 0.10000000000000001 and 0.1000000000000000055511151231257827021181583404541015625 are all approximated by 3602879701896397 / 2 ** 55. Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant eval(repr(x)) == x. Historically, the Python prompt and built-in repr() function would choose the one with 17 significant digits, 0.10000000000000001. Starting with Python 3.1, Python (on most systems) is now able to choose the shortest of these and simply display 0.1.
python2.7.11的相关文档:
引用
It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display >>> 0.1 0.1000000000000000055511151231257827021181583404541015625 That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead >>> 0.1 0.1 It’s important to realize that this is, in a real sense, an illusion: the value in the machine is not exactly 1/10, you’re simply rounding the display of the true machine value.

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧