python series tutorials 65

Friends, if you need to reprint, please indicate the source: https://blog.csdn.net/jiangjunshow

Statement: during the teaching of artificial intelligence technology, many students asked me some python related questions. Therefore, in order to let the students master more extended knowledge and better understand AI technology, I asked my assistant to share this series of python tutorials. I hope it can help you! Since this set of python tutorial was not written by me, it is not as interesting and humorous as my AI technology teaching, which is boring to learn; But its knowledge points are in place and worth reading! PS: if you can't understand this article, please read the previous article first and learn a little every day step by step, so you won't find it difficult!

Python 2.6 and Python 3.0 introduce a new number type, fraction, which implements a rational number object. It explicitly retains a numerator and a denominator, thus avoiding some imprecision and limitations of floating-point mathematics.

Fractions are the "close relatives" of the existing fixed decimal precision types introduced in the previous article. They can control the numerical precision by fixing the number of decimal places and specifying rounding or truncation strategies. Fractions are used in a way similar to decimals, which also exist in the module; A fraction can be generated by importing its constructor and passing a numerator and denominator. The following interactive example shows how to do this:

>>> from fractions import Fraction

>>> x = Fraction(1,3)  # Numerator,denominator

>>> y = Fraction(4,6)  # Simplified to 2,3 by gcd

>>> x

Fraction(1,3)

>>> y

Fraction(2,3)

>>> print(y)

2/3

Once the score is created, it can be used in mathematical expressions as usual:

>>> x + y

Fraction(1,1)

>>> x - y  # Results are exact: numerator,denominator

Fraction(-1,3)

>>> x * y

Fraction(2,9)

Fraction objects can also be created from floating-point character strings, which is very similar to decimals:

>>> Fraction('.25')

Fraction(1,4)

>>> Fraction('1.25')

Fraction(5,4)

>>>

>>> Fraction('.25') + Fraction('1.25')

Fraction(3,2)

The limitation of floating-point numbers is particularly obvious for values that cannot be accurately represented by a given finite number of bits in memory. Both fractions and decimals provide a way to get accurate results, although at the cost of some speed. For example, in the following example, the floating-point number does not give the expected answer of 0 accurately, but the other two types do it:

>>> 0.1 + 0.1 + 0.1 - 0.3  # This should be zero (close,but not exact)

5.5511151231257827e-17

>>> from fractions import Fraction

>>> Fraction(1,10) + Fraction(1,10) + Fraction(1,10) - Fraction(3,10)

Fraction(0,1)

>>> from decimal import Decimal

>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')

Decimal('0.0')

In addition, both fractions and decimals can provide more intuitive and accurate results than floating-point numbers, which they do in different ways (using rational numbers and by limiting precision):

>>> 1 / 3           # Use 3.0 in Python 2.6 for true "/"

0.33333333333333331

>>> Fraction(1,3)  # Numeric accuracy

Fraction(1,3)

>>> import decimal

>>> decimal.getcontext().prec = 2

>>> decimal.Decimal(1) / decimal.Decimal(3)

Decimal('0.33')

In fact, the scores remain accurate and automatically simplify the results. Continue with the previous interaction example:

>>> (1 / 3) + (6 / 12)  # Use ".0" in Python 2.6 for true "/"

0.83333333333333326


>>> Fraction(6,12)     # Automatically simplified

Fraction(1,2)

>>> Fraction(1,3) + Fraction(6,12)

Fraction(5,6)

>>> decimal.Decimal(str(1/3)) + decimal.Decimal(str(6/12))

Decimal('0.83')


>>> 1000.0 / 1234567890

8.1000000737100011e-07

>>> Fraction(1000,1234567890)

Fraction(100,123456789)

Fractions and floating-point numbers can be converted to each other:

>>> (2.5).as_integer_ratio()               # float object method

(5,2)

>>> f = 2.5

>>> z = Fraction(*f.as_integer_ratio())    # Convert float -> fraction: two args

>>> z                                      # Same as Fraction(5,2)

Fraction(5,2)



>>> x                                      # x from prior interaction

Fraction(1,3)

>>> x + z

Fraction(17,6)                                     # 5/2 + 1/3 = 15/6 + 2/6



>>> float(x)                               # Convert fraction -> float

0.33333333333333331

>>> float(z)

2.5

>>> float(x + z)

2.8333333333333335

>>> 17 / 6

2.8333333333333335


>>> Fraction.from_float(1.75)              # Convert float -> fraction: other way

Fraction(7,4)

>>> Fraction(*(1.75).as_integer_ratio())

Fraction(7,4)

Some types of blending are also allowed in expressions, although Fraction must sometimes be passed manually to ensure accuracy:

>>> x

Fraction(1,3)

>>> x + 2                # Fraction + int -> Fraction

Fraction(7,3)

>>> x + 2.0              # Fraction + float -> float

2.3333333333333335

>>> x + (1./3)           # Fraction + float -> float

0.66666666666666663

>>> x + (4./3)

1.6666666666666665

>>> x + Fraction(4,3)   # Fraction + Fraction -> Fraction

Fraction(5,3)

Warning: Although floating-point numbers can be converted to fractions, in some cases, there will be an inevitable loss of precision when doing so, because this number is imprecise in floating-point form.

My WeChat official account is AI knowledge sharing.

Keywords: Programming

Added by phpcat on Fri, 04 Mar 2022 09:33:57 +0200