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

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.

主站蜘蛛池模板: 榆林市| 庐江县| 保山市| 双柏县| 远安县| 高邮市| 乌鲁木齐市| 库尔勒市| 罗平县| 北安市| 眉山市| 鸡泽县| 资阳市| 达日县| 瓦房店市| 奉新县| 普洱| 富裕县| 嘉祥县| 印江| 准格尔旗| 上蔡县| 曲松县| 民和| 江孜县| 巴塘县| 绍兴县| 庆安县| 博白县| 始兴县| 镇赉县| 陵川县| 固原市| 米易县| 韶关市| 巴林左旗| 永年县| 玉龙| 济源市| 呼图壁县| 万载县|