Ask Your Question
2

How to force numerical coefficients for non-polynomials?

asked 2020-09-19 05:42:15 +0100

dsejas gravatar image

updated 2020-09-19 05:42:42 +0100

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2020-09-19 10:45:23 +0100

rburing gravatar image

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.

edit flag offensive delete link more

Comments

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!

dsejas gravatar imagedsejas ( 2020-09-22 06:28:33 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-09-19 05:42:15 +0100

Seen: 422 times

Last updated: Sep 19 '20