Ask Your Question
1

why sagemath can integrate a string?

asked 2019-12-24 07:46:54 -0500

Nasser gravatar image

I am surprised this works. Sagemath 8.9

sage: var('x')
x
sage: integrate("x",x)
1/2*x^2

sage: type("x")
<type 'str'>

Why does sagemath accept string for the integrand? Should not this be type error? Maple:

restart
int("x",x)
Error, (in int) wrong number (or type) of arguments: wrong type of integrand passed to indefinite integration.
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2019-12-24 08:53:16 -0500

dsejas gravatar image

updated 2019-12-27 11:11:15 -0500

Hello, @Nasser. This behavior is related to the code of the integrate function itself. If you execute integrate?? in your Sage session, you will be able to see the docstring of the subroutine, and its source code. We are interested in the source code right now:

if hasattr(x, 'integral'):
    return x.integral(*args, **kwds)
else:
    from sage.symbolic.ring import SR
    return SR(x).integral(*args, **kwds)

This basically verifies if the object you passed as argument (x in this code) has the integral attribute, which is nothing more than a subroutine that specifies how x should be integrated. If x doesn't have such an attribute defined, then Sage converts it into an element of the Symbolic Ring (SR).

In the case of your example, the string "x" does not have an integral attribute (since it's a string), so Sage calls SR('x'), which converts your string into the identity function, i.e. $x\mapsto x$, whose integral is $1/2x^2$.

As particular examples, you can try:

f(x) = SR("x")
f(2)

This will return 2, as expected, showing you that you have actually define a function from its string representation. Now try:

(f(x)).integral(x)

which is equivalent to integrate(f(x), x) or integrate("x", x) of (SR("x")).integral(x). Finally, try:

f(x) = SR("sin(x)")
f(pi)
(f(x)).integral(x)
integrate("sin(x)", x)

EDIT Based on the answer to this question, I must point out that the use of strings as functions, by means of the Symbolic Ring SR, is discourage and should be avoided, because it has unpleasant consequences. This kind of use of strings seems not to be documented for that reason.

I hope this helps!

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: 2019-12-24 07:46:54 -0500

Seen: 76 times

Last updated: Dec 27 '19