Python numeric type

Overview

Study notes for First Python 3rd Edition

agenda

--Numerical value --Python expressions and operators --Numerical values and usage examples --Other numeric types

Python numeric type

Numerical value

Numeric literal

Literal example Mold
1234, -24, 0 Short integer (equivalent to Long of C)
99999999999999999999L Long integer
1.23, 3.14e-10, 4E210, 4.90+210 Floating point number (equivalent to C double)
0177, 0x9ff, 0XFF Eighth or hexadecimal (integer)
3+4j, 3.0+4.0j, 3J Complex number

** Integer and floating point size and precision **

--A normal Python integer is equivalent to a C long --Floating point number is equivalent to C double --The accuracy depends on how much precision is given to long and double by the C compiler used to create the Python interpreter.

** Long integer **

--If you add l or L to an integer literal, it becomes a long integer. --You will be able to increase the accuracy infinitely --There is almost no point in adding L in the current version

** Hexagonal and octal **

--For octal integers, ** prefix with zero (0), then write a number in the range 0-7 ** --For hexadecimal numbers, ** prefix with 0x, followed by a number in the range 0-9 or a letter in the range A-F ** (either uppercase or lowercase).

** Complex number **

--Write complex numbers in the format of real + imaginary --Add j or J to the end of the imaginary part --There may be no real part, and the imaginary part can be written before the real part. --Complex numbers are treated as floating point pairs inside the system, but operations using complex numbers are performed correctly.

Built-in tools and extensions

operator

--+ ,*,>>,**, etc.

** Mathematical function (built-in function) **

--pow, ʻabs`, etc.

** Utility module **

--random, math, etc.

** Full-scale numerical meter **

Python expressions and operators

PYthon operators

operator Description
yield x Used when defining a generator function
lambda argument:formula Used to create anonymous functions
x if y else z Ternary operator
x or y Logical sum
x and y Logical AND
not x Logical denial
x < y
x <= y
x > y
x >= y
Comparison operator
x == y
x <> y
x != y
Value equivalence comparison operator
x is y
x is not y
Object comparison operator
x in y
x not in y
Operator to check if it is a member of a sequence
x | y Bit OR
x ^ y Bit exclusive OR
x & y Bit AND
x << y
x >> y
Shift operator
-x + y
x - y
Addition/Linking
Subtraction
x * y
x % y
x / y
x // y
Multiply/repetition
Surplus/String format
division
-x
+x
~x
x ** y
Invert (do not) sign
Bit inversion
Exponentiation
x[ i ]
x[ i : j ]
x.attr
x(...)
Indexing
Slicing
Attribute reference
Function call
(...)
[...]
{...}
'...'
Tuple
list
dictionary
Conversion to string

Operator combination (priority)

――It is good to show it explicitly --Use parentheses to clarify priorities

>>> (x + y) * z

>>> x + (y * z)

Mixed types in formulas

--When multiple types are mixed in one expression, Python first converts the operand types. --All operand types are aligned with the most "complex" type used --It is also done to automatically convert to a long integer when the value of the short integer becomes too large. --Automatic type conversion is done only for numeric values --In Python, pre-ranking for type "complexity"

Rank Mold
1 Complex number
2 Floating point number
3 Long integer
4 Short integer

Operator overload

--Operators may be overloaded (or newly created) by Python classes or C extensions ――This property is commonly called polymorphism. --"Function changes depending on the type of object to be processed"

Numerical values and usage examples

Numerical representation

--The value displayed without the print statement is the exact output of the hardware-derived answer.

Bit operation

#The value of x is 0001
>>> x = 1
>>> x << 2
4

#Shift 2 bits to the left to 0100
>>> x | 2
3

#OR operation to 0011#AND operation to 0001
>>> x & 1
1

Long integer

--If you add the letter L (or lowercase l) to the end of a number, it is considered a long integer. --There is a feature that you can increase the size (number of digits) as much as the memory capacity allows.

Complex number

--Represented in Python using two floating point numbers --One corresponds to the real part and the other corresponds to the imaginary part --To indicate that the number belongs to the imaginary part, add J (may be a lowercase j) at the end, and use + to combine the real and imaginary parts.

>>> 1j * 1J
(-1+0j)
>>> 2 + 1j * 3
(2+3j)
>>> (2+1j)*3
(6+3j)

Hexagonal and octal numbers

--For octal numbers, start with 0 and then arrange numbers from 0 to 7. Each digit corresponds to 3 bits. --For hexadecimal numbers, start with 0x or 0X, followed by numbers from 0 to 9 or alphabets from A to F (lowercase letters are acceptable). Each digit corresponds to 4 bits. ――Even if it is expressed in octal or hexadecimal, an integer is still an integer. --For Python, integers are output in decimal by default --Some of the built-in functions convert decimal numbers to decimal and hexadecimal numbers. --There is also a function called ʻint` that can convert 8 or hexadecimal numbers to decimal numbers. --It is also possible to convert decimal numbers to decimal and hexadecimal numbers by using a string format expression.

#8 base
>>> 01, 010, 0100
(1, 8, 64)

#Hexadecimal
>>> 0x01, 0x10, 0xFF
(1, 16, 255)

>>> oct(64), hex(64), hex(255)
('0100', '0x40', '0xff')

>>> int('0100'), int('0100', 8), int('0x40', 16)
(100, 64, 64)

>>> eval('100'), eval('0100'), eval('0x40')
(100, 64, 64)

>>> "%o %x %X" % (64, 64, 255)
'100 40 FF'

Built-in tool for numerical processing

math module


>>> import math

#Commonly used constants
>>> math.pi, math.e
(3.1415926535897931, 2.7182818284590451)

#Sine, cosine, tangent
>>> math.sin(2 * math.pi / 180)
0.034899496702500969

#square root
>>> math.sqrt(144), math.sqrt(2)
(12.0, 1.4142135623730951)


>>> abs(-42), 2**4, pow(2, 4)
(42, 16, 16)

#Truncate, round
>>> int(2.567), round(2.567), round(2.567, 2)
(2, 3.0, 2.5699999999999998)

random module


>>> import random
>>> random.random()
0.49741978338014803

>>> random.random()
0.49354866439625611

>>> random.randint(1, 10)
5

>>> random.randint(1, 10)
4

>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Life of Brian'

>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Holy Grail'

Other numeric types

Decimal type

--A new type called decimal is introduced from Python 2.4 --Use by importing a module and calling a function instead of a literal --Similar to floating point numbers, except that the number of digits after the decimal point is fixed, that is, the precision is fixed. --May cause some performance degradation compared to floating point numbers ――In order to express a numerical value with constant accuracy such as calculation of total amount, accuracy is also improved and appropriate type

For floating point type


>>> 0.1 + 0.1 + 0.1 - 0.3
5.5511151231257827e-017

>>> print 0.1 + 0.1 + 0.1 - 0.3
5.55111512313e-017

For decimal type


>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal("0.0")

set

>>> x = set('abcde')
>>> y = set('bdxyz')

>>> x
set(['a', 'c', 'b', 'e', 'd'])

#Determine if the set contains elements
>>> 'e' in x
True

#Set difference
>>> x - y
set(['a', 'c', 'e'])

#Combined sets
>>> x | y set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z'])

#Crossing of sets
>>> x & y set(['b', 'd'])

Example of using a set


>>> engineers = set(['bob', 'sue', 'ann', 'vic'])
>>> managers = set(['tom', 'sue'])

#Extract people who are both engineers and managers
>>> engineers & managers
set(['sue'])

#Extract people who belong to any category
>>> engineers | managers
set(['vic', 'sue', 'tom', 'bob', 'ann'])

#Extract people who are not managers
>>> engineers - managers
set(['vic', 'bob', 'ann'])

Third party extension

--Rational numbers

Recommended Posts

Python numeric type
Python2 string type
Python # string type
Python and NumPy numeric type inheritance relationship
Python basic course (4 numeric type / character string type)
Python callable type specification
Check Python # type identity
Python
Python --Check type of values
Python immutable type int memo
Python data type summary memo
Image data type conversion [Python]
Function argument type definition in python
[Translation] Python static type, amazing mypy!
Practice! !! Introduction to Python (Type Hints)
Python for super beginners Python # dictionary type 1 for super beginners
[python] week1-3: Number type and operation
Dynamically load json type in python
Type specified in python. Throw exceptions
[Personal memo] Python sequence type / mapping type
Master the type with Python [Python 3.9 compatible]
Python for super beginners Python # dictionary type 2 for super beginners
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Shell type
Python 2.7 Countdown
Python memorandum
Reintroduction to Python Decorators ~ Learn Decorators by Type ~
[Python] Easy argument type check with dataclass
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Use PostgreSQL data type (jsonb) from Python
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python learning basics ~ What is type conversion? ~
Python installation
python tips
Installing Python 3.4.3.
A Java programmer studied Python. (About type)
[Introduction to Udemy Python3 + Application] 21. Tuple type
Try python
Python memo
Type annotations for Python2 in stub files!
Python iterative
Python algorithm