数据类型

1.float 浮点型

Floating Point Arithmetic: Issues and Limitations(浮点数:问题和限制)

Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction

0.125

使用十进制表示(科学计算法)为:1/10 + 2/100 + 5/1000

使用二进制(计算机硬件)表示为:0.001    【0/2 + 0/4 + 1/8】

 

再如:1/10  在计算机的二进制表示为无限循环分数:【使用53为二进制表示小数部分,大约为10^-16】

0.0001100110011001100110011001100110011001100110011...

In []: format(1/10,'.50f')
Out[]: '0.10000000000000000555111512312578270211815834045410'

因此在计算机中存储的1/10不再是准确的0.1

 

Historically, the Python prompt and built-in repr() function would choose the one with 17 significant digits. 默认保留16位小数【四舍五入】

In []: format(0.1,'.50f')
Out[]: '0.10000000000000000555111512312578270211815834045410'

In []: .1+.1+.1
Out[]: 0.30000000000000004

round():最多保留16位小数。

 

如果想保留真是的浮点数,可以将小数转为分数表示float.as_integer_ratio()

In []: 0.125.as_integer_ratio()
Out[]: (1, 8)

The float.hex() method expresses a float in hexadecimal (base 16), again giving the exact value stored by your computer

In [68]: x=3.14159

In [69]: x.as_integer_ratio()    //分数,真实
Out[69]: (3537115888337719, 1125899906842624)

In [70]: x.hex()   //16进制,真实
Out[70]: '0x1.921f9f01b866ep+1'

In [71]: x==float.fromhex('0x1.921f9f01b866ep+1')
Out[71]: True

 

 

另一个有用的工具是math.fsum()函数,它有助于在求和期间减轻精度损失。它跟踪“丢失的数字”,因为值被添加到一个运行的总数中。

>>> sum([0.1] * 10) == 1.0
False
>>> math.fsum([0.1] * 10) == 1.0
True

sum可以对列表进行求和,非精确

math.fsum  也是求和,精确

 

 

 2.复数

x=a+bj   a:实部, b复部

In [26]: x
Out[26]: (10+20j)

In [27]: type(x)
Out[27]: complex

 

x.real:实部(浮点数)

  In [31]: x.real
  Out[31]: 10.0

x.imag:虚部(浮点数)

 

指数保存的也是个浮点数

In [37]: 12e4
Out[37]: 120000.0

 

 

加减乘除 :复数和实数运算-》将实数当做复数

 

常用函数:

abs(x)  复数的模

round()

max()

min()

int()

float()

 

3.整数

   pow(m, n)   <==> m**n

十进制:

二进制:以 0b或0B开头: 0B010

 八进制:以0o开头:

十六进制:以0x开头:

 

posted @ 2018-05-26 14:43  fight139  阅读(198)  评论(0编辑  收藏  举报