1. 精度
round函数, build-in function,
round( x[, n]) ,对x保留四舍五入到n位小数
2. 整除与浮点除
>>> 10/3 3 >>> 10//3 3
>>> float(10)/float(3) 3.3333333333333335
>>> float(10)//float(3) 3.0
浮点除法的另一种方法:
from __future__ import division
>>> from __future__ import division >>> 10/3 3.3333333333333335 >>> 10//3 3
>>> 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)>>> num61389表示成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.
本文探讨了Python在数值计算中遇到的一些典型问题,包括精度损失、溢出错误及高效计算策略。通过实例分析,提供了相应的解决方案和最佳实践,帮助读者理解和避免这些常见问题。
3135

被折叠的 条评论
为什么被折叠?



