# Easy way to round polynomial coefficients?

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

1
( 2024-05-06 07:57:26 +0200 )edit

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

( 2024-05-06 08:40:54 +0200 )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))

( 2024-05-06 09:25:08 +0200 )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

( 2024-05-06 09:54:37 +0200 )edit
1

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

( 2024-05-06 11:01:40 +0200 )edit