# Simplify function numerically

When I have a function that is exact, such as:

x = var("x")
fnc = sqrt(2) * x
print(fnc)


And I want to resolve/approximate all those parts of the function which can be resolved numerically, how can I do this?

fnc.n()


does not work because it throws a TypeError, similarly does

float(fnc)


I've also tried all .simplify() variants, but neither do what I want. I simply want the output to be:

print(magic_function(fnc))
1.4142 * x


How can this be done?

edit retag close merge delete

Thanks for the answer, but this doesn't work. The ExpressionTreeWalker walks coefficients/factors (e.g., the "2" in this case) but it doesn't resolve sqrt(2).

I just tried it and it does work on your example. On what expression does it not work?

1

It does indeed! I was using an ancient 2017 version of Sagemath. Once I upgraded to 9.2, it worked like advertised. Thanks for the help!

EDIT: Sorry, no, it doesn't work. Wasn't the sage version. Try this:

expr = 1.5*2^x/log(2) print(SubstituteNumericalApprox()(expr))

gives

1.50000000000000*2.00000000000000^x/log(2.00000000000000)^1.00000000000000

i.e. log(2) is not resolved.

Sort by » oldest newest most voted I've updated my answer to "is it possible to round numbers in symbolic expression" to handle functions (such as logarithms) that can be evaluated numerically:

sage: SubstituteNumericalApprox(digits=5)(1.5*2^x/log(2))
2.1640*2.0000^x

more

FWIW :

sage: (x*sqrt(2)).n()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)


[ Snip... ]

TypeError: cannot evaluate symbolic expression numerically


indeed... But :

sage: (x*sqrt(2))._sympy_().n()._sage_()
1.41421356237310*x


Nevertheless, rbunrning's answer to this (close) question is highly relevant

HTH,

more