Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 19204
1
r"""
2
Bit-level properties of integers
3
================================
4
5
The ``integer_bits`` module defines functions that
6
return bit-level properties of integers,
7
such as partity and bitwise inner product.
8
9
AUTHORS:
10
11
- Paul Leopardi (2016-08-21): initial version
12
13
"""
14
#*****************************************************************************
15
# Copyright (C) 2016-2017 Paul Leopardi [email protected]
16
#
17
# Distributed under the terms of the GNU General Public License (GPL)
18
# as published by the Free Software Foundation; either version 2 of
19
# the License, or (at your option) any later version.
20
# http://www.gnu.org/licenses/
21
#*****************************************************************************
22
23
24
from sage.rings.integer import Integer
25
26
27
base2 = lambda dim, num: Integer(num).digits(2, padto=dim)
28
r"""
29
Map ``num`` to :math:`\mathbb{F}_2^{dim}` using lexicographical ordering.
30
31
INPUT:
32
33
- ``num`` -- non-negative integer. The value to be mapped.
34
- ``dim`` -- positive integer. The Boolean dimension.
35
36
OUTPUT:
37
38
A list of 0,1 integer values of length ``dim``.
39
40
EXAMPLES:
41
42
::
43
44
sage: from boolean_cayley_graphs.integer_bits import base2
45
sage: base2(5,3)
46
[1, 1, 0, 0, 0]
47
sage: base2(3,5)
48
[1, 0, 1]
49
sage: base2(3,1)
50
[1, 0, 0]
51
"""
52
53
54
def parity(n):
55
r"""
56
Return the bit parity of a non-negative integer.
57
58
Given the non-negative number ``n``, the function ``parity`` returns 1
59
if the number of 1 bits in the binary expansion is odd, otherwise 0.
60
61
INPUT:
62
63
- ``n`` -- non-negative integer.
64
65
OUTPUT:
66
67
0 or 1, being the bit parity of ``n``.
68
69
EXAMPLES:
70
71
::
72
73
sage: from boolean_cayley_graphs.integer_bits import parity
74
sage: parity(0)
75
0
76
sage: parity(2)
77
1
78
sage: parity(3)
79
0
80
"""
81
result = False
82
while n != 0:
83
n &= n - 1
84
result = not result
85
return 1 if result else 0
86
87
88
def inner(a, b):
89
r"""
90
Return the inner product of two non-negative integers interpreted as Boolean vectors.
91
92
Given the non-negative numbers ``a`` and ``b``, the function ``inner`` returns
93
the Boolean inner product of their binary expansions.
94
95
INPUT:
96
97
- ``a`` -- non-negative integer.
98
- ``b`` -- non-negative integer.
99
100
OUTPUT:
101
102
0 or 1, being the Boolean inner product of the Boolean vectors
103
represented by ``a`` and ``b``.
104
105
EXAMPLES:
106
107
::
108
109
sage: from boolean_cayley_graphs.integer_bits import inner
110
sage: inner(0,0)
111
0
112
sage: inner(1,1)
113
1
114
sage: inner(3,3)
115
0
116
"""
117
return parity(a & b)
118
119