# How can I get mpmath to work with sage variables?

In Sage, the following code produces error messages ending with "TypeError: cannot evaluate symbolic expression numerically":

from mpmath import *
var('a')
print sqrt(a)


If I remove the line "from mpmath import *", it prints "sqrt(a)" as expected.

How can I get mpmath to work with sage variables?

edit retag close merge delete

Sort by » oldest newest most voted

To complement @vdelecroix answer, the main issue is that, when you write:

from mpmath import *


you import hundreds of functions into the namespace, overwriting the ones that are imported by Sage, this includes sqrt.

If you want to use both Sage's symbolics and mpmath numerics, you have to be more parsimonious and only import what you need. For example, if the functions you want to import from mpmath are acos and atan, you can write:

from mpmath import acos, atan


Also, perhaps a more long-term solution, if there is something that works better with mpmath than with the Sage's default (or that seems absent from Sage), you should advertise it so that we use mpmath for such a feature in Sage.

more

1

As a complement: If you ant to use both mpmath's sqrt and Sage's one, you have three options: Either you use from mpmath import sqrt as mpsqrt and call mpsqrt, or you use import mpmath and call mpmath.sqrt, or you use import mpmath as mp and call mp.sqrt. (The as ... is the way to define an alias, so you can use anything in place of mpsqrt or mp in my examples.) In all cases, sqrt still refers to Sage's function.

( 2017-12-04 10:44:29 +0100 )edit

mpmath is a library intended to compute functions to high precision. If you try to use it on a symbolic variable it will fail. The input must be numeric (and Sage numbers work well)

sage: import mpmath
sage: mpmath.sqrt(5.3)
mpf('2.3021728866442674')
sage: mpmath.sqrt(pi)
mpf('1.7724538509055159')

more

I'm attempting to do a mix of symbolic and high-precision-numeric computations in a loop. It appears (from my example above) that merely importing mpmath precludes doing any symbolic computations involving sqrt anywhere in that session.

Specifically, it appears that the "ordinary" sqrt works with symbolic variables, but that the mpmath sqrt does not. Is there a workaround?

( 2017-12-04 05:12:16 +0100 )edit

Yes: do not use from mpmath import * but say explicitely what you need to import.

( 2017-12-06 11:36:03 +0100 )edit