convert rationals to reals in symbolic expression

39 views
Skip to first unread message

Douglas Davis

unread,
May 7, 2015, 4:04:36 PM5/7/15
to sage-s...@googlegroups.com
Is there a way to convert a symbolic result from using rational expressions and constants to the corresponding expression using reals?

For example if I have a result of

-15/28*2^(2/3)*a*hh^2+32/pi*b^3

I need to convert it to

-0.85039*a*hh^2 + 10.186*b^3

Anything I try I gives  "cannot evaluate symbolic expression numerically"

I need both types of solutions for grading homework. Many expressions are more complicated and I change upstream values frequently so converting each term by hand is not practical.

I have been looking for a solution for some time.  Thank you.

Dima Pasechnik

unread,
May 7, 2015, 5:49:23 PM5/7/15
to sage-s...@googlegroups.com


On Thursday, 7 May 2015 21:04:36 UTC+1, Douglas Davis wrote:
Is there a way to convert a symbolic result from using rational expressions and constants to the corresponding expression using reals?

For example if I have a result of

-15/28*2^(2/3)*a*hh^2+32/pi*b^3

I need to convert it to

-0.85039*a*hh^2 + 10.186*b^3

Anything I try I gives  "cannot evaluate symbolic expression numerically"

I need both types of solutions for grading homework. Many expressions are more complicated and I change upstream values frequently so converting each term by hand is not practical.i

for symbolic polynomials you can use .coefficients() to extract coefficients, then you can conert them by using .n()... This is far from ideal, but still automatic.

What you could also do is substiture numbers for each variable,  and then use .n(); this way you can compute a table of numerical values...

Michael Orlitzky

unread,
May 7, 2015, 6:20:56 PM5/7/15
to sage-s...@googlegroups.com
On 05/07/2015 11:19 AM, Douglas Davis wrote:
> Is there a way to convert a symbolic result from using rational expressions
> and constants to the corresponding expression using reals?
>
> For example if I have a result of
>
> -15/28*2^(2/3)*a*hh^2+32/pi*b^3
>
> I need to convert it to
>
> -0.85039*a*hh^2 + 10.186*b^3
>

You want the (hidden!) _convert() method:

sage: a,b,hh = SR.var('a,b,hh')
sage: f = -15/28*2^(2/3)*a*hh^2+32/pi*b^3
sage: f._convert({'parent':RR})
10.1859163578813*b^3 - 0.850393420697250*a*hh^2

This is useful all the time and has been asked for before. There's a
ticket to make it public:

http://trac.sagemath.org/ticket/12577

Although now it would be nice to add some sugar on top so that e.g.
f.convert(RR) would work without the weird dict. (The dict wasn't needed
back when I created the ticket.)

Reply all
Reply to author
Forward
0 new messages