Ask Your Question

Revision history [back]

I'm pretty sure it can't be done with a built-in function, but I have written one (rather, a class) as an answer to a previous (slightly different) question: is it possible to round numbers in symbolic expression.

from sage.symbolic.expression_conversions import ExpressionTreeWalker

class SubstituteNumericalApprox(ExpressionTreeWalker):
    def __init__(self, **kwds):
        self.kwds = kwds

    def pyobject(self, ex, obj):
        if not isinstance(obj, Integer) and hasattr(obj, 'numerical_approx'):
            return obj.numerical_approx(**self.kwds)
        else:
            return obj

Here I added an exception for integers, so it works in your use case:

sage: var('t')
sage: f(t) = (4/27*t^9*log(t)^2 - 32/243*t^9*log(t) + 59/2187*t^9 - 2/21*t^7*log(t)^2)
sage: SubstituteNumericalApprox()(f(t))
0.148148148148148*t^9*log(t)^2 - 0.131687242798354*t^9*log(t) + 0.0269775948788294*t^9 - 0.0952380952380952*t^7*log(t)^2

Or in the definition of f:

sage: f(t) = SubstituteNumericalApprox()(4/27*t^9*log(t)^2 - 32/243*t^9*log(t) + 59/2187*t^9 - 2/21*t^7*log(t)^2)
sage: f
t |--> 0.148148148148148*t^9*log(t)^2 - 0.131687242798354*t^9*log(t) + 0.0269775948788294*t^9 - 0.0952380952380952*t^7*log(t)^2

It could be a nice idea to have such a class included in SageMath.