Ask Your Question
3

Simplify function numerically

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

itecMemory gravatar image

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

Comments

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 +0200 )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 +0200 )edit
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.

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

2 Answers

Sort by ยป oldest newest most voted
1

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

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))
2.1640*2.0000^x
edit flag offensive delete link more
0

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

Emmanuel Charpentier gravatar image

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

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,

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

Stats

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

Seen: 527 times

Last updated: Jan 08 '22