English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about the different numbers used in Python, how to convert one data type to another, and the mathematical operations supported in Python.
Python supports integers, floats, and complex numbers. They are defined as int, float, and complex in Python's data types.
integers and floats are separated by the presence or absence of a decimal point.5is an integer, and5.0 is a float.
complex numbers are written in the form x + yj, wherexis the real part,yis the imaginary part.
We can use the type() function to determine the data type of a variable or value, and we can use the function isinstance() to check if it belongs to a specific type.
a = 5 # Output: <class 'int'> print(type(a)) # Output: <class 'float'> print(type(5.0)) # Output: (8+3j) c = 5 + 3j print(c + 3) # Output: True print(isinstance(c, complex))
Although integers can be of arbitrary length, floating-point numbers can only be accurately represented up to15decimal places (the16bit inaccuracy).
The numbers we deal with every day are decimal (with10) number system. But computer programmers (usually embedded programmers) need to use binary (base2), hexadecimal (base16) and octal (base8) number system.
In Python, we can represent these numbers by adding prefixes before the numbers. The following table lists these prefixes.
number system | prefix |
---|---|
Binary | '0b' or '0B' |
Octal | '0o' or '0O' |
Hexadecimal | '0x' or '0X' |
Here are some examples
# Output: 107 print(0b1101011) # Output: 253 (251 + 2) print(0xFB + 0b10) # Output: 13 print(0o15)
When running the program, the output is:
107 253 13
We can convert one number to another. This is also called explicit conversion.
If one of the operands is a float, then operations like addition, subtraction, etc., will force integers to be implicitly (automatically) floated.
>>> 1 + 2.0 3.0
We can see above1(integer) is forced to be converted to1.0 (float) for addition operations, and the result is also a float.
We can also use built-in functions like int(), float(), and complex() for explicit type conversions between types. These functions can even convert fromstringconversion.
>>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>> complex('3+5j') (3+5j)
When converting float to integer, the number will be truncated (to the nearest integer).
Python's built-in class float performs some calculations that may surprise us. We all know1.1and2.2The sum is3.3But Python seems to disagree.
>>> (1.1 + 2.2) == 3.3 False
What's going on?
It turns out that floating-point numbers are implemented as binary fractions in computer hardware because computers only understand binary (0 and1)。For this reason, most of the decimal decimals we know cannot be accurately stored in our computers.
Let's take an example. We cannot represent the fraction1/3represented as a decimal number. This will give 0.33333333 ...is infinitely long, and we can only approximate it.
The original decimal decimal 0.1This will lead to an infinitely long binary fraction 0.000110011001100110011 ...while our computers only store a finite number of binary numbers.
This will only approach 0.1but will never be equal. Therefore, this is a limitation of our computer hardware, not an error in Python.
>>> 1.1 + 2.2 3.3000000000000003
To overcome this problem, we can use the decimal module that comes with Python. The precision of floating-point numbers can reach up to15decimal places, while the decimal module has precision that can be set by the user.
import decimal # Output: 0.1 print(0.1) # Output: Decimal('0.1000000000000000055511151231257827021181583404541015625') print(decimal.Decimal(0.1))
When we need to perform decimal calculations like in school, we will use this module.
It also retains meaning. We know that25.50 kilograms is more than25.5kilograms are more accurate because they have two decimal places instead of one.
from decimal import Decimal as D # Output: Decimal('3.3') print(D('1.1') + D('2.2)) # Output: Decimal('3.000') print(D('1.2') * D('2.50'))
Note the trailing zeros in the previous example.
We might ask, why not always use Decimal instead of float? The main reason is efficiency. Floating-point operations must be faster than decimal operations.
In the following cases, we usually use decimals.
When we perform financial applications that require precise decimal representation.
When we need to specify the required level of precision.
When we want to implement the concept of significant decimal places.
When we want to perform operations like in school
Python provides operations involving decimals through its fractions module.
Decimals have a numerator and denominator, both of which are integers. The module supports rational number algorithms.
We can create Fraction objects in various ways.
import fractions # Output: 3/2 print(fractions.Fraction(1.5)) # Output: 5 print(fractions.Fraction(5)) # Output: 1/3 print(fractions.Fraction(1,3))
When creating fractions from float, we may get some unexpected results. This is due to the imperfect binary floating-point representation discussed in the previous section.
Fortunately, decimals allow us to use string examples. This is the preferred option when using decimal numbers.
import fractions # Used as float # Output: 2476979795053773/2251799813685248 print(fractions.Fraction(1.1)) # Used as string # Output: 11/10 print(fractions.Fraction('1.1))
This data type supports all basic operations. Here are some examples.
from fractions import Fraction as F # Output: 2/3 print(F(1,3) + F(1,3)) # Output: 6/5 print(1 / F(5,6)) # Output: False print(F(-3,10) > 0) # Output: True print(F(-3,10) < 0)
Python provides similar modules, such as math and random, which can perform different mathematical operations, such as trigonometric functions, logarithms, probability, and statistics, etc.
import math # Output: 3.141592653589793 print(math.pi) # Output: -1.0 print(math.cos(math.pi)) # Output: 22026.465794806718 print(math.exp(10)) # Output: 3.0 print(math.log10(1000)) # Output: 1.1752011936438014 print(math.sinh(1)) # Output: 720 print(math.factorial(6))
This isIn the Python math moduleList of available complete list functions and properties.
import random # Output: 16 print(random.randrange(10,20)) x = ['a', 'b', 'c', 'd', 'e'] # Get a random option print(random.choice(x)) # Scramble the order of x list random.shuffle(x) # Print the output after x is scrambled print(x) # Print random element print(random.random())
Output result (random result):
19 c ['e', 'a', 'd', 'c', 'b'] 0.707947055817621
This isIn the Python random moduleList of available complete list functions and properties.