# How to force numerical coefficients for non-polynomials?

Hello, Sage Community!

Suppose I have a function like

f(x) = 4/27*t^9*log(t)^2 - 32/243*t^9*log(t) + 59/2187*t^9 - 2/21*t^7*log(t)^2


I would like to force Sage to write the coefficients numerically, i.e.,

f(x) = 0.148148148148148*t^9*log(t)^2 - 0.131687242798354*t^9*log(t) + 0.0269775948788294*t^9 - 0.0952380952380952*t^7*log(t)^2


Thanks in advance! Is there a way to achieve this without having to create my own specialized function?

edit retag close merge delete

Sort by ยป oldest newest most voted

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.

more

1

Thank you very much, @rburing! Your solution worked even better than what I thought originally. For example, your code works perfectly even if I have expressions inside nested inside parentheses or functions. Awesome!

( 2020-09-22 06:28:33 +0200 )edit