Ask Your Question
1

why sagemath can integrate a string?

asked 2019-12-24 14:46:54 +0200

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 15:53:16 +0200

dsejas gravatar image

updated 2019-12-27 18:11:15 +0200

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 14:46:54 +0200

Seen: 286 times

Last updated: Dec 27 '19