A discussion on the control of decimal point precision in Python

Source: Internet
Author: User



Https://www.cnblogs.com/herbert/p/3402245.html





Basis


The floating-point number is represented by the machine's double-precision (a-bit) of the floating-point number. provides approximately 17 bits of precision and ranges from 308 to 308 of the exponent. Same as the double type in the C language. Python does not support a single-precision floating-point number of 32bit. If your program requires precise control over intervals and digital precision, consider using the NumPy extension library.






Python 3.X The default for floating-point numbers is to provide 17-digit precision.






On the popular interpretation of single and double precision:



Single and double, with type specifier float single-precision specifier, double double-precision specifier. The single-precision type in turbo C accounts for 4 bytes (32-bit) of memory space, with a value range of 3.4e-38~3.4e+38 and only seven digits of valid digits. The double is a 8-byte (64-bit) memory space with a value range of 1.7e-308~1.7e+308 and a 16-bit valid number.





Requires a small precision


Convert floating-point numbers with high precision to low-precision floating-point numbers.


1.round () built-in method


This is the most used, just looked at the use of round () explanation, is not very easy to understand. Round () is not a simple rounding process.



For the built-in types supporting round (), values is rounded to the closest multiple of ten to the power minus ndigits; If double multiples is equally close, rounding is do toward the even choice (so, for example, both round (0.5) and round (-0 .5) is 0, and round (1.5) is 2).


>>> round(2.5)2>>> round(1.5)2>>> round(2.675)3>>> round(2.675, 2)2.67


Round () If there is only one number as the argument, and the number of bits is not specified, an integer is returned, and the nearest integer (which is similar to rounding). But when it comes to. 5, the distances are the same on both sides, round () takes an even number near, which is why round (2.5) = 2. When you specify the number of decimal places for a trade-off, the general situation is also the rule to use rounding, but if you encounter a. 5, if the small tree before the number of digits is odd, then discard directly if even this upward trade-off. Look at the following example:


>>> round(2.635, 2)2.63>>> round(2.645, 2)2.65>>> round(2.655, 2)2.65>>> round(2.665, 2)2.67>>> round(2.675, 2)2.67
2. Use formatting


The effect and round () are the same.


>>> a =("%.2f"%2.635)>>> a‘2.63‘>>> a =("%.2f"%2.645)>>> a‘2.65‘>>> a =int(2.5)>>> a2




Precision analysis requiring over 17 bits


Python defaults to 17 decimal places, but here's a question of what to do when our calculations need to use higher precision (more than 17 decimal places).


1. Using formatting (not recommended)
>>> a ="%.30f" %(1/3)>>> a‘0.333333333333333314829616256247‘


Can be displayed, but inaccurate, the numbers that follow are often meaningless.


2. High precision using decimal module, with GetContext
>>> fromdecimal import*>>> print(getcontext())Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])>>> getcontext().prec =50>>> b =Decimal(1)/Decimal(3)>>> bDecimal(‘0.33333333333333333333333333333333333333333333333333‘)>>> c =Decimal(1)/Decimal(17)>>> cDecimal(‘0.058823529411764705882352941176470588235294117647059‘)>>> float(c)0.058823529411764705


The default context precision is 28 bits, which can be set to 50 bits or higher. This way, when analyzing complex floating-point numbers, you can have a higher level of accuracy that you can control. In fact, you can pay attention to the context of the Rounding=round_half_even parameters. Round_half_even, when half, close to even.





About decimals and rounding


When it comes to decimals, it is necessary to speak of integers. These functions are used in general rounding:


1. Round ()


This does not say, has already spoken before. Be sure to note that it is not a simple rounding, but a round_half_even strategy.


2. Ceil (x) of the math module


Take the smallest integer greater than or equal to X.


3. Floor (x) of the math module


Go to the largest integer less than or equal to X.


 
>>> from math import ceil, floor >>> round(2.5) 2
>>> ceil(2.5) 3
>>> floor(2.5) 2
>>> round(2.3) 2
>>> ceil(2.3) 3
>>> floor(2.3) 2
>>>




Decimal module is mathematically calculated


The decimal module in Python can solve the above problems
In a decimal module, you can construct a decimal by integer, string, or principle. A Decimal object. In the case of floating-point numbers, pay particular attention to the fact that the floating-point number itself has an error and needs to be converted to a string.


>>> from decimal import Decimal
>>> from decimal import getcontext
>>> Decimal (‘4.20’) + Decimal (‘2.10’)
Decimal (‘6.30’)
>>> from decimal import Decimal
>>> from decimal import getcontext
>>> x = 4.20
>>> y = 2.10
>>> z = Decimal (str (x)) + Decimal (str (y))
>>> z
Decimal (‘6.3’)
>>> getcontext (). prec = 4 #Set precision
>>> Decimal (‘1.00‘) /Decimal(‘3.0 ’)
Decimal (‘0.3333’) 


Of course, the accuracy of the increase in the meantime, it certainly brings the loss of performance. These performance losses are worthwhile in situations where data requirements are particularly accurate, such as financial settlement. But if it is a large-scale scientific calculation, it is necessary to consider the operational efficiency. After all, the native float must be much faster than a decimal object.



A discussion on the control of decimal point precision in Python


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.