Python Tutorial中英双语对照文档4


CHAPTER
THIRTEEN


WHAT NOW?

现在咧?

Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world problems. Where should you go to learn more?
阅读这个教程可能已增强你使用 Python 兴趣 —— 你应该是踊跃去应用 Python 去解决你实际的问题. 你应该去哪里了解更多?

This tutorial is part of Python’s documentation set. Some other documents in the set are:

  • library-index:
    You should browse through this manual, which gives complete (though terse) reference material about types, functions, and the modules in the standard library. The standard Python distribution includes a lot of additional code. There are modules to read Unix mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, write CGI programs, compress data, and many other tasks. Skimming through the Library Reference will give you an idea of what’s available.
  • installing-index explains how to install additional modules written by other Python users.
  • reference-index: A detailed explanation of Python’s syntax and semantics. It’s heavy reading, but is useful as a complete guide to the language itself.
    这个教程是 Python 文档集合的一部分. 集合里的其他文档是:
  • 库索引:
    您应该浏览本手册, 这将给出标准库中关于类型, 函数, 和模块的完整()参考资料. 标准 Python 发布包括很多额外的代码. 有些模块可以去阅读 Unix 邮箱, 通过 HTTP 检索文档, 生成随机数, 解析命令行选项, 编写 CGI 程序, 压缩数据, 和更多其他的任务. 浏览 “库参考” 可以让您了解可用的内容.
  • 安装指南解释如何安装其他用户写的附加模块.
  • 语言参考: Python 语法和语义的详细解释. 它读起来很艰难, 但它作为语言本身的完整指南是有用的.

More Python resources:

  • https://www.python.org: The major Python Web site. It contains code, documentation, and pointers to Python-related pages around the Web. This Web site is mirrored in various places around the world, such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your geographical location.
  • https://docs.python.org: Fast access to Python’s documentation.
  • https://pypi.org: The Python Package Index, previously also nicknamed the Cheese Shop, is an index of user-created Python modules that are available for download. Once you begin releasing code, you can register it here so that others can find it.
  • https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a sizable collection of code examples, larger modules, and useful scripts. Particularly notable contributions are collected in a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.)
  • http://www.pyvideo.org collects links to Python-related videos from conferences and user-group meetings.
  • https://scipy.org: The Scientific Python project includes modules for fast array computations and manipulations plus a host of packages for such things as linear algebra, Fourier transforms, non-linear solvers, random number distributions, statistical analysis and the like.
    更多 Python 资源:
  • https://www.python.org: Python 官方网站. 它包含代码, 文档, 和Web 上与 Python 有关的页面. 该网站在世界各地都有镜像, 如欧洲, 日本, 和澳大利亚; 镜像可能更快比主站点, 取决于您的地理位置.
  • https://docs.python.org: 快速访问 Python 文档.
  • https://pypi.org: Python 包索引, 此前还昵称为奶酪店, 是用户创建 Python 模块索引, 它们可用来被下载. 一旦你开始发布代码, 你可以在那注册, 这样其他用户可以发现它.
  • https://code.activestate.com/recipes/langs/python/: Python Cookbook是一个相当大的代码示例集, 更大的模块和有用的脚本. 特别值得注意的贡献收集在一本名为Python Cookbook的书中(O’Reilly & Associates, ISBN 0-596-00797-3.)
  • http://www.pyvideo.org 从会议和用户组会议中收集与Python相关的视频的链接.
  • https://scipy.org: The Scientific Python 项目包含用于快速阵列计算的模块和扩展操作的一大堆包来处理线性代数, 傅里叶变换, 非线性求解器, 随机数分布, 统计分析以及类似的包.

For Python-related questions and problem reports, you can post to the newsgroup comp.lang.python, or send them to the mailing list at python-list@python.org. The newsgroup and mailing list are gatewayed, so messages posted to one will automatically be forwarded to the other. There are hundreds of postings a day, asking (and answering) questions, suggesting new features, and announcing new modules. Mailing list archives are available at https://mail.python.org/pipermail/.
对于Python相关的问题和问题报告, 你可以发到新闻组 comp.lang.python, 或发送它们到邮件列表 python-list@python.org. 新闻组和邮件列表是开放的, 所以发布到一个的消息将自动转发给另一个. 每天有上千推送, 问(或回答)问题, 提出新功能, 和发布新模块. 邮件列表档案可在 https://mail.python.org/pipermail/ 得到.

Before posting, be sure to check the list of Frequently Asked Questions (also called the FAQ). The FAQ answers many of the questions that come up again and again, and may already contain the solution for your problem.
发布之前, 请务必查看常见问题列表(又名 FAQ). FAQ 回答了大量的问题, 它们总是一再出现, 也许包含你问题的解决方案.


CHAPTER
FOURTEEN


INTERACTIVE INPUT EDITING AND HISTORY SUBSTITUTION

交互式输入编辑和历史替代

Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the GNU Readline library, which supports various styles of editing. This library has its own documentation which we won’t duplicate here.
一些 Python 解释器的版本支持当前输入行编辑和历史记录, 类似于在 Korn shell 和 GNU Bash shell 中看到的功能. 这是使用 GNU Readline 库实现的, 它支持各种编辑风格. 这个库有自己的文档, 我们不会在这里复述.

14.1 Tab Completion and History Editing

14.1 Tab 补全和历史记录

Completion of variable and module names is automatically enabled at interpreter startup so that the Tab key invokes the completion function; it looks at Python statement names, the current local variables, and the available module names. For dotted expressions such as string.a, it will evaluate the expression up to the final ‘.’ and then suggest completions from the attributes of the resulting object. Note that this may execute application-defined code if an object with a __getattr__() method is part of the expression. The default configuration also saves your history into a file named .python_history in your user directory. The history will be available again during the next interactive interpreter session.
变量和模块名的补全是自动地启用在解释器启动时, 这样 Tab 键就能调用补全功能; 它查找 Python 语句命名, 当前变量, 和可用模块名. 对于点表达式如 string.a, 它将求出表达式最后一个 ‘.’ 之前的值, 然后根据结果的属性给出补全的建议. 注意, 这可能执行应用程序定义的代码, 如果对象的 __getattr__() 方法是表达式的一部分. 默认配置还会将历史记录保存到你的用户目录下名为的 .python_history 文件中. 历史记录将在再一次进入交互式解释器回话中可用.

14.2 Alternatives to the Interactive Interpreter

14.2 交互式解释器的替代品

This facility is an enormous step forward compared to earlier versions of the interpreter; however, some wishes are left: It would be nice if the proper indentation were suggested on continuation lines (the parser knows if an indent token is required next). The completion mechanism might use the interpreter’s symbol table. A command to check (or even suggest) matching parentheses, quotes, etc., would also be useful.
与早期版本的解释器相比, 现在的施向前迈出了一大步; 然而, 一些期望依旧落空: 如果在延续线上建议适当的缩进, 那将是很好的(). 补全机制可使用解释器的符号表. 命名检查(或甚建议)匹配括弧, 引号, 等等, 将是很有用的.

One alternative enhanced interactive interpreter that has been around for quite some timeis IPython, which features tab completion, object exploration and advanced history management. It can also be thoroughly customized and embedded into other applications. Another similar enhanced interactive environment is bpython.
一个替代的增强交互式解释器已经存在很长一段时间的是 IPython, 功能有标签补全, 对象探索和先进的历史管理. 它还可以彻底定制并嵌入到其他应用程序中. 另一个类似的增强交互解释器是 bpython


CHAPTER
FIFTEEN


FLOATING POINT ARITHMETIC: ISSUES AND LIMITATIONS

浮点算术:问题和局限性

Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction

0.125

has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction

0.001

has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.

浮点数在计算机硬件中表示为基数2(二进制)分数. 例如, 十进制分数

0.125

值为 1/10 + 2/100 + 5/1000, 同样的方式在二进制中

0.001       # 注意这里 0.001 前面是整数部分是0 , 小数部分分是 001

值为 0/2 + 0/4 + 1/8. 这两个小数有相同的值, 唯一真正的区别是第一个用十进制分数表示法写成, 而第二个是二进制.

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating point numbers actually stored in the machine.
不幸地, 大多数十进制分数不能准确地被二进制表示. 后果是, 一般地, 你输入的十进制浮点数实际上只是由二进制浮点数近似地保存在机器中.

The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction:

0.3

or, better,

0.33

or, better,

0.333

and so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3.
这个问题最初在基数10中更容易理解. 考虑分数 1/3. 你可以这样近似地左基数 10 分数:

0.3

或, 更好,

0.33

或, 更好,

0.333

等等. 无论你愿意记下多少位数, 结果永远不会是真正的 1/3, 但会是越来越好的近似于 1/3.

In the same way, no matter how many base 2 digits you’re willing to use, the decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base 2, 1/10 is the infinitely repeating fraction

0.0001100110011001100110011001100110011001100110011...

同样地, 无论你用多少基数2的位数, 十进制值 0.1 将永远不会真正用基数2分数表示. 在基数 2, 1/10 是无限重复的部分

0.0001100110011001100110011001100110011001100110011...

Stop at any finite number of bits, and you get an approximation. On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two. In the case of 1/10, the binary fraction is 3602879701896397 / 2 ** 55 which is close to but not exactly equal to the true value of 1/10.
停在任何有限的位数, 你将得到一个近似数. 今天的大多数机器上, 浮点数是使用分数以最高的 53 位为分子, 2 的幂为分母的近似数. 在 1/10 的例子中, 二进制分数是 3602879701896397 / 2 ** 55

Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, 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

由于显示值的方式, 许多用户不知道近似值. Python仅将十进制近似值打印到机器存储的二进制近似值的真实十进制值. 在大多数机器上, 如果Python要打印存储为0.1的二进制近似值的真实十进制值, 则必须显示

>>> 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

>>> 1 / 10
0.1

这比大多数人认为有用的数字更多, 所以 Python 通过显示一个近似值替代来保持位数管理.

>>> 1 / 10
0.1

Just remember, even though the printed result looks like the exact value of 1/10, the actual stored value is the nearest representable binary fraction.
只要记得, 即使打印结果看起来像 1/10 的精确值, 但实际存储的值是最接近的可表示二进制分数.

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.
有趣的是, 有很多不同的十进制数共享最接近的近似二进制分数. 例如, 数字 0.1 和 0.10000000000000001 和 0.1000000000000000055511151231257827021181583404541015625 都是 3602879701896397 / 2 ** 55 的近似. 由于所有这些十进制数共享同样的近似值, 在保持恒等式 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.
历史上, Python 提示符和内置的 repr() 函数选择一个 17 位精度的数字, 0.10000000000000001. 从 Python 3.1 开始, Python(在大多数系统上)能够从这些数字当中选择最短的一个并简单地显示 0.1.

Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes).
注意, 这是二进制浮点的本质: 这不是 Python 的 bug, 也不是你代码的 bug. 你会看到在所有支持硬件浮点数算法的语言都有同样的事(虽然有些语言可能不会显示差异在默认情况或所有输出模式下).

For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits:

>>> format(math.pi, '.12g') # give 12 significant digits
'3.14159265359'
>>> format(math.pi, '.2f') # give 2 digits after the point
'3.14'
>>> repr(math.pi)
'3.141592653589793'

It’s important to realize that this is, in a real sense, an illusion: you’re simply rounding the display of the true machine value.

为了更好看的输出, 你可能希望使用字符串格式化去产生限定位数的有效数字:

>>> format(math.pi, '.12g') # give 12 significant digits
'3.14159265359'
>>> format(math.pi, '.2f') # give 2 digits after the point
'3.14'
>>> repr(math.pi)
'3.141592653589793'

One illusion may beget another. For example, since 0.1 is not exactly 1/10, summing three values of 0.1 may not yield exactly 0.3, either:

>>> .1 + .1 + .1 == .3
False

一种错觉可能会产生另一种错觉. 例如, 由于 0.1 不是精确的 1/10, 三个 0.1 和可能不会精确到 0.3, 如:

>>> .1 + .1 + .1 == .3
False

Also, since the 0.1 cannot get any closer to the exact value of 1/10 and 0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with round() function cannot help:

>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False

另外, 由于 0.1 不能更接近于 1/10 的精确值, 且 0.3 不能更接近于 3/10 的精确值, 所以用 round() 函数预取值没有帮助:

>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False

Though the numbers cannot be made closer to their intended exact values, the round() function can be useful for post-rounding so that results with inexact values become comparable to one another:

>>> round(.1 + .1 + .1, 10) == round(.3, 10)
True

虽然数字不能更接近于它们的预期的确切值, round() 函数可以用于后舍入, 这样结果的不精确值来相互比较:

>>> round(.1 + .1 + .1, 10) == round(.3, 10)
True

Binary floating-point arithmetic holds many surprises like this. The problem with “0.1” is explained in precise detail below, in the “Representation Error” section. See The Perils of Floating Point for a more complete account of other common surprises.
二进制浮点算法有很多这样的意想不到的结果. “0.1” 的问题在下面"表达错误"一节将详细解释.有关其他常见惊喜的更完整说明,请参阅浮点危险.

As that says near the end, “there are no easy answers.” Still, don’t be unduly wary of floating-point! The errors in Python float operations are inherited from the floating-point hardware, and on most machines are on the order of no more than 1 part in 2**53 per operation. That’s more than adequate for most tasks, but you do need to keep in mind that it’s not decimal arithmetic and that every float operation can suffer a new rounding error.
正如接近结尾所说, “没有简单的答案.” 不过, 不要过分担心浮点数! Python 浮点数操作的错误是继承自浮点硬件, 大多数机器上每次计算误差不超过 2**53 分之 1. 这对于大多数任务来说已经足够了, 但你需要牢记这不是十进制算法, 且每次浮点操作可能遇到一个新的四舍五入错误.

While pathological cases do exist, for most casual use of floating-point arithmetic you’ll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. str() usually suffices, and for finer control see the str.format() method’s format specifiers in formatstrings.
虽然病理情况确实存在, 对于大多数临时使用浮点运算, 你最后将看到期望的结果, 如果您只是将最终结果的显示四舍五入到您期望的小数位数. str() 一般就足够了, 而对于更细致的控制参阅格式化字符串语法str.format() 方法的格式说明符.

For use cases which require exact decimal representation, try using the decimal module which implements decimal arithmetic suitable for accounting applications and high-precision applications.
对于要求精确十进制表达的用法, 尝试使用十进制模块实现十进制计算适配会计应用和高精度应用.

Another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly).
另一种精确计算的形式是由分数模块支持的, 它实现计算基于有理数(这样想 1/3 的数可以被精确地表达).

If you are a heavy user of floating point operations you should take a look at the Numerical Python package and many other packages for mathematical and statistical operations supplied by the SciPy project. See https://scipy.org.
如果你是浮点数操作的重度使用者, 你应该看一看 Numerical Python 包和许多其他用于数学和统计学的包. 参阅 https://scipy.org.

Python provides tools that may help on those rare occasions when you really do want to know the exact value of a float. The float.as_integer_ratio() method expresses the value of a float as a fraction:

>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

Python 提供了可帮助在那些你真的想知道浮点数的确切值时的罕见场合的工具. float.as_integer_ratio() 方法表达浮点数的值为一个分数:

>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

Since the ratio is exact, it can be used to losslessly recreate the original value:

>>> x == 3537115888337719 / 1125899906842624
True

由于比值时精确的, 它可以被用于无损重建原值:

>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

The float.hex() method expresses a float in hexadecimal (base 16), again giving the exact value stored by your computer:

>>> x.hex()
'0x1.921f9f01b866ep+1'

float.hex() 方法用十六进制(基数 16)表达浮点数, 也给出你电脑的精确值保存:

>>> x.hex()
'0x1.921f9f01b866ep+1'

This precise hexadecimal representation can be used to reconstruct the float value exactly:

>>> x == float.fromhex('0x1.921f9f01b866ep+1')
True

精确十六进制表达可以用作重构浮点精确浮点值:

>>> x == float.fromhex('0x1.921f9f01b866ep+1')
True

Since the representation is exact, it is useful for reliably porting values across different versions of Python (platform independence) and exchanging data with other languages that support the same format (such as Java and C99).
由于这种表达式精确的, 它很有用于跨不同版本的Python可靠地移植值(平台独立性)和与其他支持同样格式的语言(如 Java 和 C99)交换数据.

Another helpful tool is the math.fsum() function which helps mitigate loss-of-precision during summation. It tracks “lost digits” as values are added onto a running total. That can make a difference in overall accuracy so that the errors do not accumulate to the point where they affect the final total:

>>> sum([0.1] * 10) == 1.0
False
>>> math.fsum([0.1] * 10) == 1.0
True

另一个有用工具是 math.fsum() 函数, 它帮助减轻在求和计算中的精度损失. 当值添加到运行求和时, 它会跟踪"丢失的数字". 这能对整体准确性产生影响, 这样错误不会累积到一点而这里它们影响最后的和:

>>> sum([0.1] * 10) == 1.0
False
>>> math.fsum([0.1] * 10) == 1.0
True

15.1 Representation Error

15.1 表达错误

This section explains the “0.1” example in detail, and shows how you can perform an exact analysis of cases like this yourself. Basic familiarity with binary floating-point representation is assumed.
这一节详细说明 “0.1” 示例, 教你怎样自己去精确的分析此类案例. 假设这里你已经对浮点数表示有基本的了解.

Representation error refers to the fact that some (most, actually) decimal fractions cannot be represented exactly as binary (base 2) fractions. This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many others) often won’t display the exact decimal number you expect.
表达错误是指事实上一些(大多数, 实际上)十进制分数不能精确地用二进制分数表示. 这是为什么 Python (或 Perl, C, C++, Java, Fortran, 和许多其他语言)经常不能显示你期望的精确十进制数的主要原因.

Why is that? 1/10 is not exactly representable as a binary fraction. Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”. 754 doubles contain 53 bits of precision, so on input the computer strives to convert 0.1 to the closest fraction it can of the form J/2**N where J is an integer containing exactly 53 bits. Rewriting

1 / 10 ~= J / (2**N)

as

J ~= 2**N / 10

and recalling that J has exactly 53 bits (is >= 2**52 but < 2**53), the best value for N is 56:

>>> 2**52 <= 2**56 // 10 < 2**53
True

为什么是这样的? 1/10 不能精确地表达为二进制分数. 今天(2000年11月)几乎所有的机器使用 IEEE-754 浮点运算, 几乎所有平台都将 Python 浮点数映射到 IEEE-754 “双精度”. 754 双精度包含 53 位精度, 所以计算机努力将输入的 0.1 转为 J/2**N 最接近的二进制小数. 改写:

1 / 10 ~= J / (2**N)

J ~= 2**N / 10

并回想起 J 恰好有53位(> = 2 ** 52 但 <2 ** 53)

That is, 56 is the only value for N that leaves J with exactly 53 bits. The best possible value for J is then that quotient rounded:

>>> q, r = divmod(2**56, 10)
>>> r
6

也就是说, 56是N的唯一值, 它使J正好为53位. J的最佳可能值是接下来那个商数四舍五入:

>>> q, r = divmod(2**56, 10)
>>> r
6

Since the remainder is more than half of 10, the best approximation is obtained by rounding up:

>>> q+1
7205759403792794

由于余数是超过 10 的一半, 通过四舍五入获得最好的近似值:

>>> q+1
7205759403792794

Therefore the best possible approximation to 1/10 in 754 double precision is:

7205759403792794 / 2 ** 56

因此, 在 754 双精度下取 1/10 最好可能的近似值是:

7205759403792794 / 2 ** 56

Dividing both the numerator and denominator by two reduces the fraction to:

3602879701896397 / 2 ** 55

将分子和分母都除以2将分数减少到:

3602879701896397 / 2 ** 55

Note that since we rounded up, this is actually a little bit larger than 1/10; if we had not rounded up, the quotient would have been a little bit smaller than 1/10. But in no case can it be exactly 1/10!
注意由于我们四舍五入了, 这实际上比1/10大一点; 如果我们没有收集, 商值将会小于1/10. 但在任何情况下都不能完全是1/10!

So the computer never “sees” 1/10: what it sees is the exact fraction given above, the best 754 double approximation it can get:

>>> 0.1 * 2 ** 55
3602879701896397.0

所以计算机永远不会看到 1/10: 它看到的是上面给出的确切分数, 它可得到最好的 754 双精度近似值:

>>> 0.1 * 2 ** 55
3602879701896397.0

If we multiply that fraction by 10**55, we can see the value out to 55 decimal digits:

>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625

meaning that the exact number stored in the computer is equal to the decimal value 0.1000000000000000055511151231257827021181583404541015625. Instead of displaying the full decimal value, many languages (including older versions of Python), round the result to 17 significant digits:

>>> format(0.1, '.17f')
'0.10000000000000001'

如果我们把这个分数乘以 10**55, 我们可以看到值的55位十进制:

>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625

意为着保存在计算机里的精确值等价于十进制值0.1000000000000000055511151231257827021181583404541015625. 多数语言()四舍五入结果到 17 位有效数字, 而不是显示完整的十进制值.

>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625

The fractions and decimal modules make these calculations easy:

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)
>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'

分数和十进制模块使得这些计算很容易:

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)
>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'