Python number operations (-) Numerical, hash, bitwise, Boolean and other operations

All types can be compared, detect logical values, convert strings, and all data types can perform mathematical operations.

Logical value detection

Any data type or object can be tested for logical value, and it is regarded as a true value by default, unless the object or its class redefines the bool () method and returns False or the object defines the len () method and returns zero.

The following are the objects that are considered false values ​​during logic detection:

. Constants defined as false values:None 和 False

. Zero of any numeric type:0,0.0,0j,Decimal(0),Fraction(0,1)

. Empty sequences and multinomial sets:'',(),{},set(),range(0)

Bool operation

Bool operations include  and、or、notnot> and> or in order of priority

Calculation result Annotation
x or y If x is false, then return y, otherwise return x or is a short-circuit operator, the second parameter will be evaluated only when the first parameter is a false value
x and y If x is false, then return x, otherwise return y and is also a short-circuit operator. The second parameter will be evaluated only when the first parameter is true.
not x If x is false, then return True, otherwise return False The precedence is lower than that of non-Boolean operators, so it  not a == bwill be interpreted as not (a==b)and a == not bwill cause syntax errors

Comparison operation

There are eight comparison operators in Python, with the same precedence, but all have higher precedence than Boolean operations, and comparison operators can be arbitrarily connected in series. For example, it is x<y<=zequivalent to  x< y and y <=zthat the difference is that the former y is only evaluated once, and the latter is evaluated twice. The same point is that z will not be evaluated when the result of x<y is false.

The eight comparison operators are as follows:

Operator meaning
< Less than
<= less than or equal to
> more than the
>= greater or equal to
== equal
!= not equal to
is Object ID
is not Negative object identification

Points to note in comparison operations

. Different numbers and objects of different types are never equal when compared

. Function type only supports simplified form comparison

. <,<=,>,>= operator when comparing complex numbers and other numeric types, or when two objects have different types that cannot be compared, or in other situations where the order is not defined, the above will all produce TypeErroeexceptions

. Instances of different identification classes are not equal unless the eq () method is defined

. Class instances cannot be sorted with the same class or other instances or other types of objects, unless  it (), le (), gt (), ge () are defined

is And  is notcannot be customized, can be applied to any two objects without throwing an exception.

. in And  not in , above eight kinds of comparison operators have the same priority, but only support Iterable (iterables) or implements contains Type () method

Numerical operations

All numeric types, except for complex number types, support the following operations. The priority of all numeric operations is higher than that of comparison operations. The following are arranged in ascending order of priority :

Calculation meaning
+ Sum of two numbers
- Difference between two numbers
$ \times $ Product of two numbers
/ Divide two numbers, the result is returned to the quotient
// Divide two numbers, the result returns the quotient
% Divide two numbers and take the remainder
-x x negated
+x x positive
abs(x) absolute value of x
int(x) Convert x to integer
float(x) Convert x to floating point
complex(re,im) A complex number with real part re and imaginary part im, im defaults to 0
c.conjugate() Conjugate of complex number c
divmod (x, y) Execute x//yx%y to get the quotient and remainder after x is divided by y
pow (x, y) x to the power of y
x ** y Also represents x to the power of y
invmod(x,y) 对x模y取反

数字运算注意点:

. / 除法运算返回的永远是一个浮点数

.// 整除结果值是一个整数,但结果的类型不一定是int。 运算结果永远向负无穷方向舍入, 1//2 为0, (-1)//2 为-1,1//(-2)为-1,(-1)//(-2)为0。

. % 不能用于复数

. int() 若从浮点数转换为整数会被舍入或被截断,原因在前面文章数字类型中提到过,因为二进制浮点数问题

数字类型还能进行数学函数运算,具体会在后面math和cmath模块讲到。

整数类型按位运算

按位运算只对整数有意义,按位运算优先级低于数字运算,高于比较运算,但一元运算~与其它一元算术运算符优先级相同。

运算 含义 说明
x\ y x和y按位或  
x^y x和y按位异或  
x&y x和y按位与  
x<<n x左移n位 负的移位会引发ValueError,左移n位等价于不带溢出检测的乘以pow(2,n)
x>>n x右移n位 负的移位同样会引发ValueErroe,右移n位等价于不带溢出检测的除以pow(2,n)
~x x按位取反

数字类型的哈希运算

不同数字类型的两个数,要做== 比较运算时,必须转成哈希值,即hash(x)==hash(y)。为便于在各种数字类型上实现并保证效率,Python对数字类型的哈希运算是基于任意有理数定义统一的数学函数,本质上hash()是通过以一个固定质数P进行P降模。P的值在 Python 中可以 sys.hash_info 的 modulus 属性的形式被访问。

CPython implementation detail: 所用质数设定,在 C long 为 32 位的机器上 P = 2**31 - 1 而在 C long 为 64 位的机器上 P = 2**61 - 1

运算规则如下:

  • 如果 x = m / n 是一个非负比例数,且 n 不能被 P 整除,则定义 hash(x) 为 m * invmod(n, P) % P
  • 如果 x = m / n 是一个非负比例数,且 n 能被 P 整除(但 m 不能)则 n 不能对 P降模,以上规则不适用;在此情况下则定义 hash(x) 为常数值 sys.hash_info.inf
  • 如果 x = m / n 是一个负比例数,则定义 hash(x) 为 -hash(-x)。 如果结果哈希值为 -1 则将其替换为 -2
  • 特定值 sys.hash_info.inf-sys.hash_info.inf 和 sys.hash_info.nan 被用作正无穷、负无穷和空值(所分别对应的)哈希值。 (所有可哈希的空值都具有相同的哈希值)
  • 对于一个 complex 值 z,会通过计算 hash(z.real) + sys.hash_info.imag * hash(z.imag) 将实部和虚部的哈希值结合起来,并进行降模 2**sys.hash_info.width 以使其处于 range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)) 范围之内。 同样地,如果结果为 -1 则将其替换为 -2

为了更好的理解运算规则,用代码实现如下:

对分数求哈希值:

>>> import sys,math
>>> def hash_fraction(m,n):
    '''计算比例数m/n的哈希值,m和n为整数,n为正数'''
    P = sys.hash_info.modulus
    #去掉P的公因数,除非m和n互质
    while m%P == n%P ==0:
        m,n = m//P, n//P
    #如果n能被P整除,hash值为固定值
    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        #如果n不能被P整除,则对P进行降模处理
        hash_value = (abs(m)%P)*pow(n,P-2,P)%P
    #判断m是否是负数,对负数求hash
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

对float浮点数类型求哈希值:

>>> def hash_float(x):
    #计算浮点数x的哈希值
    if math.isnan(x):
        return sys.hash_info.nan
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

对复数类型求哈希值:

#计算复数z的哈希值
    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    M = 2 **(sys.hash_info.width - 1)
    hash_value = (hash_value & (M-1)) - (hash_value&M)
    if hash_value == -1:
        hash_value = -2
    return hash_value

Decimal运算实例

Decimal 进行 $+ 、- 、\times 、/$ 运算

>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> sum (data)
Decimal('19.29')
>>> min(data)
Decimal('0.03')
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> a,b,c = data[:3]
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')
>>> a + b + c
Decimal('6.66')
>>> a - b
Decimal('-0.53')
>>> 

当余数运算%应用于Decimal对象时,结果的符号是被除数的符号,而不是除数的符号

>>> -5 % 8
3
>>> Decimal(-5) % Decimal(8)
Decimal('-5')
>>> Decimal(8) % Decimal(-5)
Decimal('3')

同样Decimal也可以进行一些数学函数运算

>>> Decimal(2).sqrt()
Decimal('1.41421')
>>> Decimal(1).exp()
Decimal('2.71828')
>>> Decimal(10).ln
<built-in method ln of decimal.Decimal object at 0x1073b04a8>
>>> Decimal(10).ln()
Decimal('2.30259')
>>> Decimal('10').log10()
Decimal('1')

关于四舍五入,Decimal的quantize()方法可以将数字四舍五入为固定函数

>>> Decimal('7.325').quantize(Decimal('0.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')

Fraction运算实例

Fraction同样可以进行$+、-、\times /$ 四则运算和%运算等

>>> from fractions import Fraction
>>> import math
>>> Fraction(2,3) + Fraction(3,5)
Fraction(19, 15)
>>> Fraction(2,3) - Fraction(3,5)
Fraction(1, 15)
>>> Fraction(2,3) * Fraction(3,5)
Fraction(2, 5)
>>> Fraction(2,3) / Fraction(3,5)
Fraction(10, 9)
>>> Fraction(2,3) % Fraction(-3, 5)
Fraction(-8, 15)
>>> Fraction(2,3) % Fraction(3,5)
Fraction(1, 15)

Fraction没有sqrt()、exp()等函数方法。

参考文献:

1.https://docs.python.org/zh-cn/3.6/contents.html

Guess you like

Origin blog.csdn.net/u010670117/article/details/115059100