Ask Your Question

Simplify function numerically

asked 2022-01-03 19:06:07 +0100

itecMemory gravatar image

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

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

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


does not work because it throws a TypeError, similarly does


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

1.4142 * x

How can this be done?

edit retag flag offensive 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).

itecMemory gravatar imageitecMemory ( 2022-01-05 09:12:09 +0100 )edit

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

rburing gravatar imagerburing ( 2022-01-05 23:03:39 +0100 )edit

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))



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

itecMemory gravatar imageitecMemory ( 2022-01-07 12:14:26 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted

answered 2022-01-08 17:54:18 +0100

rburing gravatar image

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))
edit flag offensive delete link more

answered 2022-01-08 22:24:01 +0100

Emmanuel Charpentier gravatar image

updated 2022-01-08 22:25:25 +0100


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_()

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


edit flag offensive delete link more

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


Asked: 2022-01-03 19:06:07 +0100

Seen: 506 times

Last updated: Jan 08 '22