Python基础入门----数字,类型转换和数学

Python Numbers, Type Conversion and Mathematics

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

 

Table of Contents

Python 数字,类型转换和数学

在这篇文章例,你将学习到不同的数字类型,怎么把一个数据类型转换成另外一个,在python中支持数学运算。

表格内容

  • Python的数字数据类型
  • 类型转换
  • Python小数
  1. 什么时候使用小数代替浮点数
  • Python分数
  • Python数学

Number Data Type in Python

Python supports integers, floating point numbers and complex numbers. They are defined as intfloat and complex class in Python.

Integers and floating points are separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is a floating point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

Python数据类型 

 Python支持整数,浮点数和负数。他们被定义为int,float和complex类在Python中。

整数和浮点数的区分是存在或不存在小数点。5是整数,然而5.0是浮点数。

复数编写的形式是x + yj,x是实部,y是虚部。


We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.

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

While integers can be of any length, a floating point number is accurate only up to 15 decimal places (the 16th place is inaccurate).

Numbers we deal with everyday are decimal (base 10) number system. But computer programmers (generally embedded programmer) need to work with binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.

我们可以使用type()函数去了解变量或一个值所属的类,ininstance()函数去检查它是否属于特殊的类。

整数可以是任何长度,一个浮点数仅仅精确到15位(到第16位就不准确了)。

In [1]: a = 5

In [2]: print(type(a))
<class 'int'>

In [3]: print(type(5.0))
<class 'float'>

In [4]: c = 5 + 3j

In [5]: print(c + 3)
(8+3j)

In [6]: print(isinstance(c,complex))
True

我们每天处理的数字是十进制(以10为基数)数系统。但是电脑程序员(通常的嵌入式程序员)需要工作在二进p制(以2 位基数),十六进制(以16位基数)和8进制(以8位基数)的数字系统。

 


In Python, we can represent these numbers by appropriately placing a prefix before that number. Following table lists these prefix.

Number system prefix for Python numbers
Number SystemPrefix
Binary'0b' or '0B'
Octal'0o' or '0O'
Hexadecimal'0x' or '0X'

 在Python中,我们可以在数字前面放置恰当的前缀代表这些输,下面表格列出这些前缀。

Python数字的数字系统前缀
数据系统前缀
二进制'0b' or '0B'
八进制'0o' or '0O'
十六进制'0x' or '0X'

Here are some examples

# Output: 107
print(0b1101011)

# Output: 253 (251 + 2)
print(0xFB + 0b10)

# Output: 13
print(0o15)

When you run the program, the output will be:

107
253
13

这里有一些例子

当我们执行程序时,结果输出如下:

In [10]: print(0b1101011)
107

In [11]: print(0xFB + 0b10)  //(251 + 2)
253

In [12]: print(0o15)
13

 


Type Conversion

 

We can convert one type of number into another. This is also known as coercion.

Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operand is float.

>>> 1 + 2.0
3.0

类型转换 

我们能将一个数据类型转换成另一种。众所周知这是强迫。

如果一个操作数是浮点数,操作像加法,减法强制重整数隐式的转化为浮点数(自动的)。

In [13]: 3 + 2.0
Out[13]: 5.0

We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point number.

We can also use built-in functions like int()float() and complex() to convert between types explicitly. These function can even convert from strings.

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

When converting from float to integer, the number gets truncated (integer that is closer to zero).

我们看上面,在加法宗1(整型)是强制转化为1.0(浮点型) ,这个结果还是浮点数。

我们使用内置函数像int(),float()和complex之间类型转换是很清晰的。这些函数甚至可以转化为字符串。

In [14]: int(2.8)
Out[14]: 2

In [15]: int(2.3)
Out[15]: 2

In [16]: int(-2.8)
Out[16]: -2

In [17]: float(5)
Out[17]: 5.0

In [18]: complex(3+5j)
Out[18]: (3+5j)


Python Decimal

Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree.

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

 Python小数

Python内置类float执行一些计算可能令我们吃惊,我们知道1.1加2.2的总和是3.3,但是Python似乎看起来不相等的。

In [19]: (1.1 + 2.2) == 3.3
Out[19]: False

What is going on?

It turns out that floating-point numbers are implemented in computer hardware as binary fractions, as computer only understands binary (0 and 1). Due to this reason, most of the decimal fractions we know, cannot be accurately stored in our computer.

Let's take an example. We cannot represent the fraction 1/3 as a decimal number. This will give 0.33333333... which is infinitely long, and we can only approximate it.

Turns out decimal fraction 0.1 will result into an infinitely long binary fraction of 0.000110011001100110011... and our computer only stores a finite number of it.

发生了什么?

事实证明,在电脑硬件中浮点数被执行时二进制分数,因为电脑仅仅理解二进制(0和1)。由于这个理由,我们知道的大多数小数,不能精确存储在我们的电脑。

让我们看一个例子。我们不能表达分数1/3为一个小数。它应该是0.33333333...无限长的,我们仅仅无限接近它。

事实证明,小数分数0.1的结果是一个0.000110011001100110011...无限长度的二进制,我们的电脑仅仅能存储有限数。


This will only approximate 0.1 but never be equal. Hence, it is the limitation of our computer hardware and not an error in Python.

>>> 1.1 + 2.2
3.3000000000000003

To overcome this issue, we can use decimal module that comes with Python. While floating point numbers have precision up to 15 decimal places, the decimal module has user settable precision.

import decimal

# Output: 0.1
print(0.1)

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

This module is used when we want to carry out decimal calculations like we learned in school.

 它仅仅接近0.1但是决不相等,因此,它在我们电脑硬件被限制而不是在Python中是一个错误。

In [20]: 1.1 + 2.2
Out[20]: 3.3000000000000003

克服这些问题,我们可以使用Python自带的十进制模式 。浮点数有限制15位小数点,十进制模式用户可以设置精确位数。

In [22]: print(0.1)
0.1

In [23]: print(decimal.Decimal(0.1))
0.1000000000000000055511151231257827021181583404541015625

It also preserves significance. We know 25.50 kg is more accurate than 25.5 kg as it has two significant decimal places compared to 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'))

Notice the trailing zeroes in the above example.

We might ask, why not implement Decimal every time, instead of float? The main reason is efficiency. Floating point operations are carried out must faster than Decimal operations.

它也有保留意义。我知道25.50kg更精确,比25.5kg有2位小数更有意义。

In [28]: from decimal import Decimal as D

In [29]: print(D('1.1') + D('2.2'))
3.3

In [30]: print(D('1.2') * D('2.50'))
3.000

When to use Decimal instead of float?

We generally use Decimal in the following cases.

  • When we are making financial applications that need exact decimal representation.
  • When we want to control the level of precision required.
  • When we want to implement the notion of significant decimal places.
  • When we want the operations to be carried out like we did at school

什么时候用十进制代替浮点数? 

我们一般使用十进制有以下情况。

  • 当我们开发金融应用需要用精确十进制表达。
  • 当我们想有控制精确等级需求的时候。
  • 当我们想去实现由意义小数位数概念的时候。
  • 当我们想像在学校那样进行运算。

Python Fractions

Python provides operations involving fractional numbers through its fractions module.

A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic.

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

Python分数 

python通过fraction模块提供的操作涉及了分数。

一个分数有分子和分母,两个都是整数。这模块提供有理数运算。

我们可以用各种各样方式创建分数对象。

In [33]: import fractions

In [34]: print(fractions.Fraction(1.5))
3/2

In [35]: print(fractions.Fraction(5))
5

In [36]: print(fractions.Fraction(1,3))
1/3

While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary floating point number representation as discussed in the previous section.

Fortunately, Fraction allows us to instantiate with string as well. This is the preferred options when using decimal numbers.

import fractions

# As float
# Output: 2476979795053773/2251799813685248
print(fractions.Fraction(1.1))

# As string
# Output: 11/10
print(fractions.Fraction('1.1'))

当我们从float创建分数,我们可能获得一些不寻常的结果。这是由于上节讨论的二进制浮点数表达是不完美的。 

幸运的,分数允许我们去实例化为字符串。这是优先操作当我们使用分数。

In [39]: import fractions

In [40]: print(fractions.Fraction(1.1))
2476979795053773/2251799813685248

In [41]: print(fractions.Fraction('1.1'))
11/10

This datatype supports all basic operations. Here are few 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)

这数据类型支持所有基础操作。这里有些例子。

In [44]: from fractions import Fraction as F

In [45]: print(F(1,3) + F(1,3))
2/3

In [46]: print(1 / F(5,6))
6/5

In [47]: print(F(-3,10) > 0)
False

In [48]: print(F(-3,10) < 0)
True

 


Python Mathematics

Python offers modules like math and random to carry out different mathematics like trigonometry, 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))

 Python数学

python提供模块像math和random来执行不同的数学,像三角函数,对数,概率和统计学,等等。

In [49]: import math

In [50]: print(math.pi)
3.141592653589793

In [51]: print(math.cos(math.pi))
-1.0

In [52]: print(math.exp(10))
22026.465794806718

In [53]: print(math.log10(1000))
3.0

In [54]: print(math.sinh(1))
1.1752011936438014

In [56]: print(math.factorial(6))
720

Here is the full list functions and attributes available in Python math module.

import random

# Output: 16
print(random.randrange(10,20))

x = ['a', 'b', 'c', 'd', 'e']

# Get random choice
print(random.choice(x))

# Shuffle x
random.shuffle(x)

# Print the shuffled x
print(x)

# Print random element
print(random.random())

Here is the full list functions and attributes available in Python random module.

这里有完整列表函数和属性可用在python math模块。

In [59]: import random

In [60]: print(random.randrange(10,20))
16

In [61]: x =['a','b','c','d','e']

In [62]: print(random.choice(x))
b

In [63]: random.shuffle(x)   //打乱x

In [64]: print(x)
['b', 'a', 'd', 'e', 'c']   //打印打乱的x

In [65]: print(random.random())
0.30264465041100697

 这里有完整列表函数和属性可用在python random模块。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值