官术网_书友最值得收藏!

Representation error

It should be noted that the native double precision representation of floating point numbers leads to some unexpected results. For example, consider the following:

This is a result of the fact that most decimal fractions are not exactly representable as a binary fraction, which is how most underlying hardware represents floating point numbers. For algorithms or applications where this may be an issue, Python provides a decimal module. This module allows for the exact representation of decimal numbers and facilitates greater control properties such as rounding behavior, number of significant digits, and precision. It defines two objects, a Decimal type, representing decimal numbers, and a Context type, representing various computational parameters such as precision, rounding, and error handling. An example of its usage can be seen in the following snippet:

Here we have created a global context and set the precision to 4. The Decimal object can be treated pretty much as you would treat an int or a float. They are subject to all the same mathematical operations and can be used as dictionary keys, placed in sets, and so on. In addition, Decimal objects also have several methods for mathematical operations, such as natural exponents, x.exp(), natural logarithms, x.ln(), and base 10 logarithms, x.log10().

Python also has a fractions module that implements a rational number type. The following example shows several ways to create fractions:

It is also worth mentioning here the NumPy extension. This has types for mathematical objects such as arrays, vectors, and matrixes, and capabilities for linear algebra, calculation of Fourier transforms, eigenvectors, logical operations, and much more.

主站蜘蛛池模板: 越西县| 绥阳县| 凤冈县| 探索| 全州县| 甘孜| 靖宇县| 息烽县| 大英县| 桃园市| 霍山县| 巫溪县| 巴南区| 清新县| 寿宁县| 厦门市| 潮州市| 孟州市| 汶川县| 那坡县| 新沂市| 新沂市| 北辰区| 安西县| 南雄市| 建湖县| 三原县| 红安县| 太原市| 池州市| 古交市| 攀枝花市| 龙游县| 玉田县| 临漳县| 宁明县| 朝阳区| 汉川市| 积石山| 许昌县| 葵青区|