Easy way to round polynomial coefficients?

asked 2024-05-06 07:15:44 +0100

AndrewAndrew gravatar image

updated 2024-05-06 07:49:42 +0100

FrédéricC gravatar image

y = 2.66778786276411e493t^3x - 1.93258971534823e247*x

round(y,2) or something similar is possible? To get:

y = 2.67*t^3*x - 1.93*x
edit retag flag offensive close merge delete

Comments

1

var('tx, x, t') from sage.symbolic.expression_conversions import ExpressionTreeWalker

y = 2.66778786276411e493*t^3*x - 1.93258971534823e247*x

SubstituteNumericalApprox(digits=3)(y)

Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 1, in <module> NameError: name 'SubstituteNumericalApprox' is not defined

AndrewAndrew gravatar imageAndrewAndrew ( 2024-05-06 08:40:54 +0100 )edit
1

from sage.symbolic.expression_conversions import ExpressionTreeWalker

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

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

        def __call__(self, ex):
            result = super().__call__(ex)
            return result.numerical_approx(**self.kwds) if result in CC else result


    var('t')
    y = 2.66778786276411e493*t^3*x - 1.93258971534823e247*x
    print(SubstituteNumericalApprox(digits=3)(y))
tolga gravatar imagetolga ( 2024-05-06 09:25:08 +0100 )edit

OK. Very grateful. The outcome of that is:

2.67e493*t^3.00*x - 1.93e247*x

The first term there means there are 493 decimal places still? It should be reduced to

2.67*t^3*x - 1.93*x
AndrewAndrew gravatar imageAndrewAndrew ( 2024-05-06 09:54:37 +0100 )edit
1

e493 means 10^493. Use show(SubstituteNumericalApprox(digits=3)(y)) to see it better.

tolga gravatar imagetolga ( 2024-05-06 11:01:40 +0100 )edit