My friends, for reprint please indicate the source: blog.csdn.net/jiangjunsho…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!

I don’t know if you have encountered the following strange phenomenon, the same expression but different display results. The first is the automatic echo in interactive prompt mode, and the second is the print statement display:

>>> b/(2.0 + a) >>> print (b/(2.0 + a)) # print rounds off digits 0.8Copy the code

The real reason behind this strange result is the hardware limitations of floating point and its inability to accurately represent some values. Since computer architecture is beyond the scope of this tutorial, we’ll briefly explain that the first output is actually stored in the computer’s floating-point hardware, just that you’re not used to looking at it. If you don’t want to see all the bits, use print.

Note, though, that not all values have so many digits to display:

>>> 1/2.0 0.5Copy the code

And in addition to printing and automatic echo, there are many ways to display the number of digits in a computer:

>>> Num = 1/3.0 >>> Num # Echoes 0.333333333333331 >>> Print (num) # print rounds 0.33333333333333 >>> '%e' % num # String formatting expression '3.333333E-001' >>> '%4.2f' % num # Alternative floating-point format '0.33' >>> '{0:4.2f}'. Format (num) # String formatting method (Python 2.6 and 3.0) '0.33'Copy the code

The last three of these methods use string formatting, a tool for flexible formatting that we’ll cover in a future article.