Python Digital Series-Infinity and Nan

Source: Internet
Author: User

Infinity and Nan Problems

You want to create or test floating-point numbers with positive infinity, negative infinity, or Nan (not a number).

Solution Solutions

Python does not have a special syntax to represent these special floating-point values, but it can be used float() to create them. Like what:

 >>> a = float ( Span class= "S1" > ' inf ' ) >>> b = float ( '-inf ' ) >>> span class= "n" >c = float ( ' nan ' ) >>> ainf>>> b-inf>>> cnan>>>              

In order to test the existence of these values, use math.isinf() and math.isnan() functions. Like what:

Math.  Isinf(a)Truemath.  isNaN(c)True>>>          
Discuss

For more information about these special floating-point values, you can refer to the IEEE 754 specification. However, there are some places that you need to pay special attention to, especially when it relates to comparisons and operators.

Infinite numbers are propagated when performing mathematical calculations, such as:

Float(' inf ')gb inf0.0>>>    

However, some operations are undefined and return a nan result. Like what:

Float(' inf ')a/ananfloat('-inf ')bnan>> >             

The Nan value propagates across all operations without generating an exception. Like what:

Float(' nan ')is2 nan2 nanmath.  sqrt(c)nan>>>          

A special place for Nan values when a comparison operation between them always returns false. Like what:

Float(' nan ')float(' nan ')DfalseDfalse>>> 

For this reason, testing a nan is worth the only safe way to use it math.isnan() , as demonstrated above.

Sometimes programmers want to change the python default behavior and throw an exception in an operation that returns an infinity or Nan result. The fpectl module can be used to change this behavior, but it is not enabled in standard Python builds, it is platform-dependent, and is targeted at expert programmers. You can refer to the online Python documentation for more details.

Python Digital Series-Infinity and Nan

Related Article

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.