7
$\begingroup$

I want to do something like this:

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
session = WolframLanguageSession()

a = 1e20
session.evaluate(wlexpr(f"NIntegrate[x,{{x,0,{a}}}]"))

But in Python, str(1e20) is "1e+20" which can not be recognized by Wolfram. If I cannot use f-string or str to pass a float number, what should I do?

$\endgroup$
0

2 Answers 2

7
$\begingroup$

I believe the recommended way in such case is to use wolframclient.serializers.export. However, you can generally avoid any string conversion by typing in Mathematica expressions as pure python objects/functions.

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
from wolframclient.serializers import export

session = WolframLanguageSession()

# Method 1
a = 1e20
session.evaluate(wl.NIntegrate(wl.x, [wl.x, 0, a]))

# Method 2
a = export(1e20).decode()
session.evaluate(wlexpr(f"NIntegrate[x,{{x,0,{a}}}]"))
$\endgroup$
2
  • $\begingroup$ For method 1 you actually don't need the export :) . $\endgroup$
    – xzczd
    Apr 18 at 9:48
  • $\begingroup$ @xzczd, oh, right, of course, thanks! :) $\endgroup$
    – Domen
    Apr 18 at 9:52
6
$\begingroup$

Well, I'd argue this is actually a python question about string formatting. Related discussion in meta:

Are questions about calling Mathematica in other languages/softwares on-topic?

Anyway, according to e.g. this post:

from wolframclient.evaluation import WolframLanguageSession

from numpy import format_float_positional as myform 

session = WolframLanguageSession()

a = 1e20
session.evaluate(f"NIntegrate[x,{{x,0,{myform(a)}}}]")

But, if you just want to pass argument(s), why not define a function?:

from wolframclient.evaluation import WolframLanguageSession

session = WolframLanguageSession()

a = 1e20
func=session.function("NIntegrate[x, {x, 0, #}]&")
func(a)
$\endgroup$
2
  • $\begingroup$ Thanks for your answer! I didn’t know this format_float_positional function before. In fact, I wrote a similar function myself to do this. But I think this method is too ugly, because each variable needs to be covered with an extra function. Maybe I could map(format_func,my_variables), but that doesn't seem very pretty either. $\endgroup$ Apr 18 at 9:16
  • $\begingroup$ @HaoenZhang See my update. $\endgroup$
    – xzczd
    Apr 18 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.