- 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.
- Flask Web全棧開發(fā)實戰(zhàn)
- 從零開始:數(shù)字圖像處理的編程基礎(chǔ)與應(yīng)用
- The Android Game Developer's Handbook
- 小程序?qū)崙?zhàn)視頻課:微信小程序開發(fā)全案精講
- 構(gòu)建移動網(wǎng)站與APP:HTML 5移動開發(fā)入門與實戰(zhàn)(跨平臺移動開發(fā)叢書)
- HTML5 移動Web開發(fā)從入門到精通(微課精編版)
- Ext JS Data-driven Application Design
- PyQt從入門到精通
- 機械工程師Python編程:入門、實戰(zhàn)與進階
- C++程序設(shè)計基礎(chǔ)教程
- 單片機C語言程序設(shè)計實訓(xùn)100例
- C#開發(fā)案例精粹
- Visual C++從入門到精通(第2版)
- C# 7.0本質(zhì)論
- Mastering Machine Learning with R