我使用evalf
和subs
来计算表达式。
result_1 = (1/x).evalf(subs={x: 3.0}, n=25)
result_2 = (1/x).subs(x, 3.0).evalf(25)
字符串
首先使用evalf计算表达式1/x
后,result_1
近似等于0.3333333333333333333333333
(精度设置为25)。但result_2
近似等于0.3333333333333333148296163
。
我想知道这是如何运作的幕后。
我会为任何信息和资源的链接greatful。
2条答案
按热度按时间ve7v8dk21#
让我们关注这行代码:
字符串
{x: 3.0}
被evalf
处理,这将创建一个新的字典,其中所有浮点数都将具有指定的精度。从本质上讲,新字典看起来像:{x: Float(3.0, precision=29)}
。注意我使用了precision=29
。这不是一个错误:从sympy 1.12开始,evalf
将精度增加4个单位。然后,这个字典被替换到表达式中,如下所示:
(1/x).subs({x: Float(3.0, precision=29)})
:这会触发一个求值,生成一个精度为n=29的新浮点数。最后,evalf
计算结果,直到达到用户指定的精度,在本例中n=25。第二行代码:
型
这里,
subs
将把数字3.0 sympify 为Float(3.0, precision=15)
(默认精度)。这个数字在表达式中被替换,这会触发一个计算,产生一个精度为15的新浮点数。最后,evalf
计算该数字,直到精度n=25。主要的区别是第一行代码产生一个精确的结果,直到指定的精度n=25,而第二个数字只是一些近似值,因为初始计算是在精度=15的情况下执行的。
参考:源代码,特别是
sympy/core/eval.py
dxxyhpgq2#
TL;DR
字符串
为
型
现在,将
evalf()
应用于它将是:型
它会给予
型
所以,
型
在15位之后,它失去精度。
链接到eval()
(1/x).evalf(subs={x: 3.0}, n=25)
试图避免替换可能发生的重要性损失。替换的默认精度是15位,不足以保留该信息
链接到
evalf()
https://github.com/sympy/sympy/blob/master/sympy/core/evalf.py的
您也可以通过执行
help(sympy.evalf)
来阅读详细信息名称sympy.core.evalf
描述SymPy表达式的自适应数值计算,使用数学函数的mpmath。
CLASSES builtins.ArithmeticError(builtins.Exception)PrecisionExhausted builtins.object EvalfMixin
型
FUNCTIONS N(x,n=15,**options)调用x.evalf(n,**options)。
型
DATA Any = typing.Any Special type表示不受约束的类型。
型