Basics
#N(expr, <args>)函数与sympify(expr).evalf(<args>)等价
>>> from sympy import *
>>> N(sqrt(2)*pi)
4.44288293815837
>>> (sqrt(2)*pi).evalf()
4.44288293815837
#额外的参数用于确认精确度
>>> N(sqrt(2)*pi, 5)
4.4429
>>> N(sqrt(2)*pi, 50)
4.4428829381583662470158809900606936986146216893757
#支持复数
>>> N(1/(pi + I), 20)
0.28902548222223624241 - 0.091999668350375232456*I
#有变量时进行部分计算
>>> x = Symbol('x')
>>> (pi*x**2 + x/3).evalf()
3.14159265358979*x**2 + 0.333333333333333*x
#也可以用标准python函数
>>> float(pi)
3.1415926535...
>>> complex(pi+E*I)
(3.1415926535...+2.7182818284...j)
#理论上无精确度上限
>>> str(N(pi, 10**6))[-50:]
'95678796130331164628399634646042209010610577945815'
Floating-point numbers
>>> Float(0.1)
0.100000000000000
>>> Float(0.1, 10)
0.1000000000
>>> Float(0.125, 30)
0.125000000000000000000000000000
>>> Float(0.1, 30) #传数值经精度比较低
0.100000000000000005551115123126
#解决方案
>>> Float('0.1', 30) #传字符串
0.100000000000000000000000000000
>>> Float(Rational(1, 10), 30) #传Rational变量
0.100000000000000000000000000000
>>> Rational(1, 10).evalf(30) #对Rational变量进行求值
0.100000000000000000000000000000
#以精确度较高的位数作为最终结果精确度
>>> Float(0.1, 3)*Float(3.1415, 5)
0.31417
Accuracy and error handling
#普通python计算无法进行高精度计算
>>> a, b = GoldenRatio**1000/sqrt(5), fibonacci(1000)
>>> float(a)
4.34665576869e+208
>>> float(b)
4.34665576869e+208
>>> float(a) - float(b)
0.0
#可以用N方法实现
>>> N(fibonacci(100) - GoldenRatio**100/sqrt(5))
-5.64613129282185e-22
#精度更高时N方法也失效
>>> N(fibonacci(1000) - (GoldenRatio)**1000/sqrt(5))
0.e+85
#加入maxn参数
>>> N(fibonacci(1000) - (GoldenRatio)**1000/sqrt(5), maxn=500)
-4.60123853010113e-210
#高精度计算比较耗时,加入strict抛出错误
>>> N(fibonacci(1000) - (GoldenRatio)**1000/sqrt(5), strict=True)
#传入0时N函数无法得知,用chop参数剔除
>>> f = fibonacci(100) - (GoldenRatio**100 - (GoldenRatio-1)**100)/sqrt(5)
>>> N(f)
0.e-104
>>> N(f, maxn=1000)
0.e-1336
>>> N(f, chop=True)
0
>>> N(3 + I*f, chop=True)
3.00000000000000
#round函数四舍五入,保留指定位小数
>>> v = 10*pi + cos(1)
>>> N(v)
31.9562288417661
>>> v.round(3)
31.956
Numerical simplification
#nsimplify用于化简,第二个参数为化简的类型,tolerance为误差
>>> nsimplify(0.1)
1/10
>>> nsimplify(6.28, [pi], tolerance=0.01)
2*pi
>>> nsimplify(pi, tolerance=0.01)
22/7
>>> nsimplify(pi, tolerance=0.001)
355
---
113
>>> nsimplify(0.33333, tolerance=1e-4)
1/3
>>> nsimplify(2.0**(1/3.), tolerance=0.001)
635
---
504
>>> nsimplify(2.0**(1/3.), tolerance=0.001, full=True)
3 ___
\/ 2