Python 数值计算的一些常见问题 --- 长期维护

来源:互联网 发布:企业网络拓扑 编辑:程序博客网 时间:2024/05/17 09:28


1. 精度

round函数, build-in function,
round( x[, n]) ,对x保留四舍五入到n位小数
2. 整除与浮点除
>>> 10/33>>> 10//33
>>> float(10)/float(3)3.3333333333333335
>>> float(10)//float(3)3.0
浮点除法的另一种方法:
from __future__ import division
>>> from __future__ import division>>> 10/33.3333333333333335>>> 10//33
 

>>> from __future__ import division

可以改变这种状况 让'/'除变成float除

这里有一个小小的陷阱 当做负数的除法时 因为取整的关系 -11/2 得到的结果并不是想象中的-5 而是-6(取整 不是四舍五入)

>>> -11/2 -6

引入division后得到的结果是5.5

>>> -11/2 -5.5

这里需要注意

在Python 3中 '/' 除 表示的就是float除 不需要再额外引入模块,

即使分子分母都是int, 返回的也会是一个float浮点数

 
3.字符串与数值转换
字符串转化为数字,及选择进制
>>> str1 = '0x10'
>>> num = int(str1 , 16)
>>> num
61389表示成16进制:0xEFCD
可以通过工厂函数int()和hex()相互转化:
num1= int('0xEFCD',16)
num2 = hex(61389)
 
4.  Built-in numeric functions:

abs, 

divmod,

cmp, 

coerce, 

float, 

hex, 

int, 

long, 

max, 

min, 

oct,

pow, 

round

5. Advanced numeric functions:

(The functions in the math module don’t apply to complex numbers)

from math import *

The math module provides the following functions and constants:

acos, 

asin, 

atan, 

atan2, 

ceil, 

cos, 

cosh, 

e, 

exp, 

fabs, 

floor, 

fmod,

frexp, 

hypot, 

ldexp, 

log, 

log10, 

mod, 

pi, 

pow, 

sin, 

sinh, 

sqrt, 

tan,

tanh

6. Complex numbers:

>>> (3+2j)

(3+2j)

>>> (4+4j) + (3+2j)

(7+6j)

>>> (1+2j) * (3+4j)

(-5+10j)

>>> 

>>> a = (1+5j)

>>> a.real

1.0

>>> a.imag

5.0

7.  cmath module:

(The similar functions in math module, which can operate on complex numbers, are provided in the cmath module)

import cmath

acos, acosh, asin, asinh, atan, atanh, cos, cosh, e, exp, log, log10,

pi, sin, sinh, sqrt, tan, tanh.