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

本文探讨了Python在数值计算中遇到的一些典型问题,包括精度损失、溢出错误及高效计算策略。通过实例分析,提供了相应的解决方案和最佳实践,帮助读者理解和避免这些常见问题。


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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值