3.1小节完成

This commit is contained in:
XiongNeng
2014-09-07 23:32:42 +08:00
parent a029d14c6e
commit 2effea2f95
4 changed files with 114 additions and 9 deletions

7
cookbook/c03/__init__.py Normal file
View File

@@ -0,0 +1,7 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""

37
cookbook/c03/p01_round.py Normal file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 四舍五入运算
Desc :
"""
def round_num():
print(round(1.23, 1))
print(round(1.27, 1))
print(round(-1.27, 1))
print(round(1.25361,3))
# 舍入数为负数
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
# 格式化输出
x = 1.23456
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.3f}'.format(x))
# 不要自以为是的用round去修正一些精度问题
a = 2.1
b = 4.2
c = a + b
print(c)
c = round(c, 2) # "Fix" result (???)
print(c)
if __name__ == '__main__':
round_num()

View File

@@ -5,14 +5,77 @@
----------
问题
----------
todo...
你想对浮点数执行指定精度的舍入运算。
|
----------
解决方案
----------
todo...
对于简单的舍入运算使用内置的round(value, ndigits)函数即可。比如:
.. code-block:: python
>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254
>>>
当一个值刚好在两个边界的中间的时候round函数返回离它最近的偶数。
也就是说对1.5或者2.5的舍入运算都会得到2。
传给round()函数的ndigits参数可以是负数这种情况下舍入运算会作用在十位、百位、千位等上面。比如
.. code-block:: python
>>> a = 1627731
>>> round(a, -1)
1627730
>>> round(a, -2)
1627700
>>> round(a, -3)
1628000
>>>
|
----------
讨论
----------
todo...
不要将舍入和格式化输出搞混淆了。
如果你的目的只是简单的输出一定宽度的数你不需要使用round()函数。
而仅仅只需要在格式化的时候指定精度即可。比如:
.. code-block:: python
>>> x = 1.23456
>>> format(x, '0.2f')
'1.23'
>>> format(x, '0.3f')
'1.235'
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'
>>>
同样,不要试着去舍入浮点值来"修正"表面上看起来正确的问题。比如,你可能倾向于这样做:
.. code-block:: python
>>> a = 2.1
>>> b = 4.2
>>> c = a + b
>>> c
6.300000000000001
>>> c = round(c, 2) # "Fix" result (???)
>>> c
6.3
>>>
对于大多数使用到浮点的程序,没有必要也不推荐这样做。
尽管在计算的时候会有一点点小的误差,但是这些小的误差是能被理解与容忍的。
如果不能允许这样的小误差(比如涉及到金融领域)那么就得考虑使用decimal模块了下一节我们会详细讨论。

View File

@@ -2,12 +2,10 @@
第三章:数字日期和时间
=============================
Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries.
For the most part, the use of these structures is straightforward. However,
common questions concerning searching, sorting, ordering, and filtering often arise.
Thus, the goal of this chapter is to discuss common data structures and algorithms
involving data. In addition, treatment is given to the various data structures contained
in the collections module.
Python中执行整数和浮点数的数学运算时很简单的。
尽管如此,如果你需要执行分数、数组或者是日期和时间的运算的话,就得做更多的工作了。
本章集中讨论的就是这些主题。
Contents: