English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Funzione in Python

Tipi di dati in Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python Numbers, Type Conversion and Math

In this article, you will learn about different numbers used in Python, how to convert one data type to another, and the mathematical operations supported in Python.

Number data types in Python

Python supports integers, floating-point numbers and complex numbers. They are defined as int, float and complex in Python data types.

Integers and floating-point numbers are separated by the presence or absence of a decimal point. 5 is an integer, while 5.0 is a floating-point number.

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 any length, floating-point numbers can only be accurate to 15 decimal places (the 16th place is not accurate).

The numbers we deal with every day are decimal (base 10) number systems. But computer programmers (usually embedded programmers) need to use binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.

In Python, we can represent these numbers by adding prefixes before the numbers. The following table lists these prefixes.

Prefixes for Python numbers
Number SystemPrefix
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)
# 输出: 13
print(0o15)

运行该程序时,输出为:

print(0xFB + 0b10)
# Output: 13
print(0o15)

Eseguendo il programma, l'output è:

107

253

13
Conversione di tipo di dati

Possiamo convertire un numero da un tipo numerico a un altro. Questo si chiama anche conversione forzata.

Possiamo anche utilizzare le funzioni built-in come int(), float() e complex() per effettuare conversioni esplicite tra tipi. Queste funzioni possono anche convertire daStringaConversione.

>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)

Quando si converte da float a intero, il numero viene troncato (vicino allo zero).

Decimali in Python

La classe integrata float di Python esegue alcuni calcoli che potrebbero sorprenderci. Sappiamo tutti che la somma di 1.1 e 2.2 è 3.3, ma Python sembra non essere d'accordo.

>>> (1.1 + 2.2) == 3.3
False

Cosa sta succedendo?

In realtà, i numeri a virgola mobile sono implementati come frazioni binarie nei computer hardware, poiché i computer comprendono solo binario (0 e 1). Per questo motivo, la maggior parte dei numeri decimali che conosciamo non possono essere memorizzati accuratamente nei nostri computer.

Facciamo un esempio. Non possiamo rappresentare la frazione 1/3 come numero decimale. Questo darebbe 0.33333333 ... infinito, possiamo solo approssimarlo.

Il numero decimale originale 0.1 causerebbe una frazione binaria infinita 0.000110011001100110011 ... mentre i nostri computer memorizzano solo una quantità limitata di numeri binari.

Questo si avvicinerà a 0.1, ma non sarà mai uguale. Pertanto, questa è una limitazione dell'hardware del nostro computer, non un errore in Python.

>>> 1.1 + 2.2
3.3000000000000003

Per superare questo problema, possiamo utilizzare il modulo decimale incluso in Python. La precisione dei numeri a virgola mobile può raggiungere al massimo 15 cifre decimali, mentre il modulo decimale ha una precisione configurabile dall'utente.

import decimal
# Output: 0.1
print(0.1)
# Output: Decimal('0.1000000000000000055511151231257827021181583404541015625')
print(decimal.Decimal(0.1))

当我们要像在学校学习的那样进行十进制计算时,将使用此模块。

它也保留了意义。我们知道,25.50公斤比25.5公斤更准确,因为它有两位小数,而不是一位。

from decimal import Decimal as D
# 输出: Decimal('3.3')
print(D('1.1') + D('2.2'))
# 输出: Decimal('3.000')
print(D('1.2') * D('2.50'))

注意上例中的尾随零。

我们可能会问,为什么不每次都执行Decimal而不是float?主要原因是效率。进行浮点运算必须比十进制运算更快。

何时使用Decimal而不是float?

在以下情况下,我们通常使用十进制。

  • 当我们进行需要精确十进制表示的金融应用程序时。

  • 当我们要指定所需的精度水平时。

  • 当我们想实现小数位有效的概念时。

  • 当我们希望像在学校一样进行运算时

Python 分数

Python通过其fractions模块提供涉及小数的运算。

小数具有分子和分母,它们都是整数。该模块支持有理数算法。

我们可以通过多种方式创建Fraction对象。

import fractions
# 输出: 3/2
print(fractions.Fraction(1.5))
# 输出: 5
print(fractions.Fraction(5))
# 输出: 1/3
print(fractions.Fraction(1,3))

从float创建分数时,我们可能会得到一些异常的结果。这是由于上一节中讨论的二进制浮点数表示不完善所致。

幸运的是,小数还允许我们使用字符串示例化。这是使用十进制数字时的首选选项。

import fractions
# 用作 float
# 输出: 2476979795053773/2251799813685248
print(fractions.Fraction(1.1))
# 用作 string
# 输出: 11/10
print(fractions.Fraction('1.1'))

此数据类型支持所有基本操作。这里有几个示例。

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)

Matematica Python

Python fornisce moduli simili, math e random possono eseguire diversi calcoli matematici, come funzioni trigonometriche, logaritmi, probabilità e statistiche, ecc.

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))

Questo èNel modulo math di PythonElenco completo delle funzioni e delle proprietà disponibili.

import random
# Output: 16
print(random.randrange(10, 20))
x = ['a', 'b', 'c', 'd', 'e']
# Ottieni opzione casuale
print(random.choice(x))
# Disordina l'ordine della lista x
random.shuffle(x)
# Stampa output dopo aver disordinato l'ordine di x
print(x)
# Stampa elemento casuale
print(random.random())

Risultato di output (risultato casuale):

19
c
['e', 'a', 'd', 'c', 'b']
0.707947055817621

Questo èNel modulo random di PythonElenco completo delle funzioni e delle proprietà disponibili.