- Python Data Structures and Algorithms
- Benjamin Baka
- 266字
- 2021-07-09 19:45:02
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.
- Learning PostgreSQL
- Vue.js前端開發(fā)基礎(chǔ)與項目實戰(zhàn)
- 機器人Python青少年編程開發(fā)實例
- Python 3破冰人工智能:從入門到實戰(zhàn)
- PHP+MySQL+Dreamweaver動態(tài)網(wǎng)站開發(fā)實例教程
- Python機器學習編程與實戰(zhàn)
- Python數(shù)據(jù)分析從0到1
- 微信小程序項目開發(fā)實戰(zhàn)
- 數(shù)據(jù)結(jié)構(gòu)習題解析與實驗指導
- Learning OpenCV 3 Computer Vision with Python(Second Edition)
- MongoDB,Express,Angular,and Node.js Fundamentals
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設計原理(第2版)
- 小程序從0到1:微信全棧工程師一本通
- Android Studio開發(fā)實戰(zhàn):從零基礎(chǔ)到App上線 (移動開發(fā)叢書)
- Python 快速入門(第3版)